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

React刷新页面报错Cannot read properties of undefined (reading 'userName')

问题根因

  • 初始状态类型不匹配:你将userData的初始值设为了{}空对象,但从接口取值逻辑data[0].userName可以看出来接口返回的是数组类型。组件首次渲染时会先读取初始值,此时userData[0]为undefined,读取undefined.userName就会直接抛出类型错误。你说的首次加载正常是开发环境热更新的偶发情况,刷新页面走完整组件生命周期,必然会先触发初始状态的渲染,所以会稳定复现报错。
  • 请求逻辑顺序错误:现有代码先解析返回值、更新状态,再判断响应状态码,就算请求失败也会执行setUserData,也可能触发取值报错。

修复方案

  1. 修正初始状态类型,将数组类型的初始值改为空数组:
// 修改前
const [userData, setUserData] = useState({})
// 修改后
const [userData, setUserData] = useState([])
  1. 渲染处添加空值防护,避免数据未请求完成、数组为空时的报错:
// 修改前
{userData[0].userName}
// 修改后(添加可选链,可按需加兜底展示)
{userData?.[0]?.userName ?? '用户信息加载中'}
  1. 调整请求逻辑顺序,先判断响应状态正常再处理返回数据:
const getUserData = async () => {
  debugger
  try {
    const res = await fetch('http://localhost:4000/api/authenticate', {
      method: 'GET',
      headers: {
        Accept: 'application/json',
      },
      credentials: 'include',
    })
    console.log(res)
    // 先判断状态码,异常直接抛出
    if (res.status !== 200) {
      const error = new Error(res.error)
      throw error
    }
    const data = await res.json()
    console.log('.........here i m in header dropdown...........')
    console.log(data[0].userName)
    setUserData(data)
  } catch (err) {
    console.log(err)
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:45:04