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

React报Unhandled Rejection (TypeError)读取undefined的'error'属性如何解决?

React Home组件报错排查与解决方案

错误根因

报错指向第13行if (data.error),核心原因是getProducts()的Promise resolve回调中拿到的data值为undefined,访问undefined的error属性触发类型错误,常见诱因有3个:

  • 接口请求异常(网络错误、后端报错)时没有编写catch逻辑捕获rejected状态
  • coreapicalls中封装的getProducts方法没有正确返回响应数据,导致then中拿到的data为空
  • useEffect未加依赖数组,组件重复渲染触发多次并发请求,可能引发返回值异常

修复方案

1. 优化请求逻辑,添加非空判断与异常捕获

修改loadAllProducts方法如下:

const loadAllProducts = () => {
    getProducts()
    .then((data) => {
        // 先判断data是否存在再读取属性
        if (data?.error) {
            setError(data.error);
            // useState是异步更新,直接打印error拿不到最新值,改为打印data.error
            console.log(data.error);
        } else if (data) {
            setProducts(data);
        }
    })
    // 添加catch捕获请求异常
    .catch((err) => {
        console.error("获取产品列表失败: ", err);
        setError("请求异常,请刷新重试");
    })
};

2. 修正useEffect依赖,避免无限重复请求

给useEffect添加空依赖数组,仅在组件首次挂载时触发一次请求:

useEffect(() => {
    loadAllProducts();
}, []); // 空依赖数组限定仅执行一次

3. 校验getProducts封装逻辑

打开./helper.js/coreapicalls文件,确认getProducts方法请求成功后正确返回了响应数据,以fetch封装为例:

export const getProducts = () => {
    return fetch("你的产品列表接口地址")
    .then(res => {
        if (!res.ok) throw new Error("接口响应状态异常");
        return res.json(); // 必须return转换后的json数据,否则外部then拿到的就是undefined
    })
}

修改完成后可在then回调中打印data值,确认接口返回格式符合预期即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:45:07