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

React+Firebase刷新页面时出现Cannot read properties of undefined错误

问题:React+Firebase个人资料页面刷新时出现Cannot read properties of undefined: (reading 'name')错误

使用Firebase和React搭建个人资料页面时,遇到错误提示Cannot read properties of undefined: (reading 'name')。保存代码更改时不会出现该错误,只有刷新页面时才会触发。

页面状态对比

  • 保存代码后的页面状态:
    保存代码后的页面状态
  • 刷新localhost后的页面状态:
    刷新localhost后的页面状态

当前代码

useEffect(() => {
  onAuthStateChanged(auth, async (user) => {
    if (user) {
      const snapshot = await getDoc(doc(db, "users", user.uid))
      console.log(snapshot.data().name)
      const userData= snapshot.data();
      
      setProfile(userData);

    } 
  });
}, []);

return (
  <>
    
    <Card>
      <Card.Body>
        <h2 className="text-center mb-4"> Profile</h2>
        <p className="details">
        {JSON.stringify(profile.name)}
        </p>
        {error && <Alert variant="danger">{error}</Alert>}
      </Card.Body>
    </Card>
    <div className="w-100 text-center mt-2">
      <Button variant="link" onClick={handleLogout}>
        {" "}
        Log out{" "}
      </Button>
    </div>
  </>
);
};

目前暂时使用JSON.stringify(profile)可以正常运行,但仍想弄清楚该问题的原因。


问题原因及解决方法

核心原因

刷新页面时,React组件会重新初始化,此时profile的初始值是undefined(或你设置的初始空值),而组件会在useEffect中的异步请求完成前就完成首次渲染,这时候访问profile.name就会触发“读取undefined的name属性”的错误。

而保存代码时属于热重载,React会保留之前的组件状态(profile已经有值了),所以不会触发错误。

具体分析

  1. 组件挂载后,useEffect才会执行,里面的onAuthStateChanged和getDoc都是异步操作,需要等待Firebase返回用户数据后才会调用setProfile(userData)更新状态。
  2. 首次渲染(刷新页面)时,profile还没被赋值,此时profile是初始状态(大概率是undefined),直接访问profile.name自然报错。
  3. 热重载时,组件状态没有被重置,profile已经有之前请求到的数据,所以渲染时不会出错。

解决方法

你可以通过以下几种方式避免这个错误:

  • 可选链操作符:访问属性时加上?.,即使profile是undefined也不会报错:
    {JSON.stringify(profile?.name)}
    
  • 条件渲染:确保profile存在后再渲染对应内容:
    {profile && <p className="details">{JSON.stringify(profile.name)}</p>}
    
  • 设置初始状态:给profile设置一个包含name属性的初始值,比如:
    const [profile, setProfile] = useState({ name: '' });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 15:17:35