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

Next.js调用isAuth()取属性报Cannot read property 'username' of undefined求助

报错原因

  • Next.js默认会先在服务端执行页面组件的渲染逻辑,此时process.browser值为false,你的isAuth()函数在服务端执行时,没有匹配到任何return分支,最终返回undefined,直接访问undefined.username就会抛出类型错误。
  • 你写的isAuth()函数本身逻辑存在缺漏:除了localStorage.getItem('user')不存在时会返回false之外,process.browser为假、cookieChecked为空的两个分支都没有定义返回值,默认返回undefined而非你预期的false。
  • 热更新时代码仅在客户端侧重载,此时已经是浏览器环境,isAuth()能正常返回用户对象,所以偶尔会正常运行;刷新页面会重新触发服务端渲染,所以必然复现报错。

修复步骤

1. 补全isAuth()函数的返回逻辑

把所有分支的返回值补全,避免出现返回undefined的情况:

export const isAuth = () => {
  if (process.browser) {
    const cookieChecked = getCookie('token');
    if (cookieChecked) {
      if (localStorage.getItem('user')) {
        return JSON.parse(localStorage.getItem('user'));
      }
    }
  }
  // 所有不满足条件的分支统一返回false
  return false;
};

2. 访问属性前增加空值校验

使用可选链操作符?.避免访问空值的属性报错,改写你的调用代码:

{ isAuth()?.username ? console.log(isAuth().username) : "" }

如果你的项目不支持可选链语法,也可以用逻辑与的写法:

{ isAuth() && isAuth().username ? console.log(isAuth().username) : "" }

3. 客户端侧执行依赖浏览器环境的逻辑

如果你的业务逻辑仅需要在客户端执行,可以把相关逻辑放到useEffect钩子中,useEffect只会在浏览器端运行,不会触发服务端执行报错:

import { useEffect } from 'react';

// 在你的组件内添加以下逻辑
useEffect(() => {
  const user = isAuth();
  if (user?.username) {
    console.log(user.username);
  }
}, []);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:54:02