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

React项目本地正常部署Vercel报错:Cannot read properties of undefined (reading 'includes')

问题原因

你遇到的报错是因为**pathname 为 undefined**,导致调用 includes 方法时触发类型错误。

本地运行正常但Vercel部署出错的核心原因:React Router的useLocation Hook依赖浏览器环境的window.location对象,而Vercel在部署时会执行服务器端渲染(SSR)或静态生成(SSG),此时服务器环境中没有浏览器的location上下文,useLocation会返回undefined,解构出来的pathname自然也是undefined。

另外你加的// eslint-disable-next-line react-hooks/rules-of-hooks注释是错误的——这个组件本身是合法使用Hook的,但Hook的执行环境不对,服务器端无法提供Hook所需的路由上下文。

修复方案

提供几种可行的修复方式,选一种适合你的场景:

方式一:添加浏览器环境判断,避免服务器端执行路由逻辑

修改Loadable组件,先判断是否处于浏览器环境,再处理pathname:

const Loadable = (Component) => (props) => {
  const location = useLocation();
  // 给pathname设置默认值,避免undefined
  const currentPathname = location?.pathname || '';

  return ( 
    <Suspense
      fallback={<LoadingScreen isDashboard={currentPathname.includes("/dashboard")} />}
    >
      <Component {...props} />
    </Suspense>
  );
};

方式二:用状态管理客户端路径,延迟执行路由判断

通过useEffect在客户端组件挂载后再获取路径,初始值设为空字符串:

const Loadable = (Component) => (props) => {
  const [pathname, setPathname] = useState('');
  const location = useLocation();

  useEffect(() => {
    if (location?.pathname) {
      setPathname(location.pathname);
    }
  }, [location]);

  return ( 
    <Suspense
      fallback={<LoadingScreen isDashboard={pathname.includes("/dashboard")} />}
    >
      <Component {...props} />
    </Suspense>
  );
};

方式三:确保组件仅在客户端渲染

如果你的项目支持动态导入,可以让Loadable组件只在浏览器端执行:

// 假设Loadable组件单独导出,在使用时用动态导入禁用SSR
const LoadableComponent = dynamic(() => import('./Loadable'), {
  ssr: false,
  loading: () => <LoadingScreen isDashboard={false} />
});
额外注意
  • 不要随意禁用React Hook规则,你的场景里Hook用法本身没问题,问题出在执行环境不匹配。
  • 部署前可以尝试在本地模拟SSR环境测试(比如用react-dom/server渲染组件),提前发现这类环境差异问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 21:12:22