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

Next.js项目执行npm run build时出现读取email未定义错误求助

解决Next.js npm run build 时的 Cannot read properties of undefined (reading 'email') 错误

问题根源

这个错误是因为构建阶段props.user为undefined,导致访问props.user.email时触发类型错误。虽然你通过TypeScript接口定义了user为User类型,但类型检查仅在编译阶段生效,运行/构建时如果实际传入的user未初始化或缺失,就会出现该问题。

修复方案

方案1:添加user存在性检查(推荐)

先判断props.user是否存在,不存在时返回加载状态或提示,避免直接访问其属性:

import { auth } from "@/firebase";
import { signOut, User } from "firebase/auth";
import { PrettyChatWindow } from "react-chat-engine-pretty";

interface ChatProps {
  user?: User; // 将user改为可选类型,匹配实际可能的传入情况
}

export default function Page(props: ChatProps) {
  // 未获取到用户时显示加载状态
  if (!props.user) {
    return <div>Loading...</div>;
  }

  return (
    <div style={{ height: "100vh" }}>
      <button
        style={{ position: "absolute", top: "0px", left: "0px" }}
        onClick={() => signOut(auth)}
      >
        Sign Out
      </button>
      <PrettyChatWindow
        projectId="This is the ID I use for chatengine"
        username={props.user.email || "harmse688@gmail.com"}
        secret={props.user.uid}
        style={{ height: "100%" }}
      />
    </div>
  );
}

方案2:使用可选链操作符

如果不想添加额外的渲染判断,可以用可选链?.直接处理undefined情况:

<PrettyChatWindow
  projectId="This is the ID I use for chatengine"
  username={props.user?.email || "harmse688@gmail.com"}
  secret={props.user?.uid || ""}
  style={{ height: "100%" }}
/>

方案3:客户端监听用户状态(更可靠)

如果该页面是客户端组件,建议直接在组件内通过Firebase监听用户登录状态,而非依赖外部传入user props,彻底避免undefined问题:

import { auth } from "@/firebase";
import { signOut, User, onAuthStateChanged } from "firebase/auth";
import { PrettyChatWindow } from "react-chat-engine-pretty";
import { useState, useEffect } from "react";

export default function Page() {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // 监听用户登录状态变化
    const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
      setUser(currentUser);
      setLoading(false);
    });

    // 组件卸载时取消监听
    return unsubscribe;
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (!user) {
    return <div>请登录后访问聊天功能</div>;
  }

  return (
    <div style={{ height: "100vh" }}>
      <button
        style={{ position: "absolute", top: "0px", left: "0px" }}
        onClick={() => signOut(auth)}
      >
        Sign Out
      </button>
      <PrettyChatWindow
        projectId="This is the ID I use for chatengine"
        username={user.email || "harmse688@gmail.com"}
        secret={user.uid}
        style={{ height: "100%" }}
      />
    </div>
  );
}

额外检查点

  • 如果页面通过getStaticProps/getServerSideProps传递user,需确保这些函数能稳定返回用户数据,或在获取失败时处理undefined情况;
  • 确认Firebase Auth初始化逻辑在构建阶段已正确执行,避免因Auth实例未就绪导致无法获取用户信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 14:25:24