You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React组件报错:onLoginSuccess is not a function 求助排查

问题排查与修复方案

错误原因分析

报错Error logging in: onLoginSuccess is not a function的核心诱因有两点:

  1. 组件提前卸载:在AuthorLogin的handleSubmit方法中,先执行了navigate('/writingPortfolio')触发路由跳转,直接卸载当前AuthorLogin组件,后续调用onLoginSuccess()时,组件实例已销毁,props中的函数引用失效。
  2. 缺少容错校验:未对onLoginSuccess的类型做前置判断,极端情况下(如props未正确传递)会直接抛出类型错误。

修复方案

方案1:调整执行顺序(优先推荐)

将onLoginSuccess()的调用放在路由跳转之前,确保函数在组件卸载前执行完成:

const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    try {
        const response = await axios.post('http://localhost:5000/api/author/login', formData);
        console.log('Login successful:', response.data);
        // 先执行登录成功回调,再触发路由跳转
        onLoginSuccess(); 
        navigate('/writingPortfolio');
    } catch (error) {
        console.error('Error logging in:', error.response ? error.response.data.message : error.message);
        setError(error.response ? error.response.data.message : error.message);
    }
    setLoading(false);
};

方案2:添加容错校验

在调用onLoginSuccess前增加类型判断,避免非函数类型导致的报错:

// 在handleSubmit的try块中修改
if (typeof onLoginSuccess === 'function') {
    onLoginSuccess();
}
navigate('/writingPortfolio');

额外验证:确认路由渲染逻辑

检查项目路由配置,确保AuthorLogin是通过ParentComponent渲染的,而非直接在路由中单独注册。如果路由中存在以下错误写法:

<Route path="/login" element={<AuthorLogin />} />

会导致onLoginSuccess props未传递,需改为:

<Route path="/login" element={<ParentComponent />} />

修复后关键代码示例

const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    try {
        const response = await axios.post('http://localhost:5000/api/author/login', formData);
        console.log('Login successful:', response.data);
        // 先校验再执行回调,最后跳转
        if (typeof onLoginSuccess === 'function') {
            onLoginSuccess();
        }
        navigate('/writingPortfolio');
    } catch (error) {
        console.error('Error logging in:', error.response ? error.response.data.message : error.message);
        setError(error.response ? error.response.data.message : error.message);
    }
    setLoading(false);
};

内容的提问来源于stack exchange,提问作者Phx_DPyrexx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 15:53:14