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

用户注册遇Uncaught (in promise) TypeError错误求助

错误原因与修复方案

错误根源

触发Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'user')的核心原因:

  • authAction.js中的userRegister异步Thunk在注册成功时未返回任何数据,导致authSlice里userRegister.fulfilled处理函数的payload为undefined
  • 代码直接尝试读取payload.user,自然抛出类型错误

修复步骤

方案1:修改异步Thunk,返回后端数据

在authAction.js的userRegister函数中,注册成功时返回后端返回的完整数据,确保payload有值:

export const userRegister = createAsyncThunk(
  "auth/register",
  async (
    { name, role, email, password, phone, organisationName, address, hospitalName, website },
    { rejectWithValue }
  ) => {
    try {
      const response = await fetch("http://localhost:8080/api/v1/auth/register", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name, role, email, password, phone, organisationName, address, hospitalName, website }),
      });

      const data = await response.json();

      if (data?.success) {
        alert("User Registered Successfully");
        // 后端若返回token,存入localStorage保证后续认证
        if (data.token) localStorage.setItem("token", data.token);
        // 返回数据给fulfilled处理函数
        return data;
        // 推荐用React Router的navigate跳转替代window.location,避免页面刷新丢失状态
        // navigate("/login");
      } else {
        // 处理后端返回的业务错误
        return rejectWithValue(data.message || "Registration failed");
      }
    } catch (error) {
      console.error(error);
      return rejectWithValue(error.message || "An error occurred during registration");
    }
  }
);

方案2:修改Slice的fulfilled处理,增加空值判断

如果不需要在Redux中存储注册后的用户信息,可直接修改authSlice.js的userRegister.fulfilled逻辑,避免读取不存在的属性:

builder.addCase(userRegister.fulfilled, (state, { payload }) => {
  state.loading = false;
  // 先判断payload是否存在,再赋值user
  state.user = payload?.user || null;
});

额外优化建议

  • 替换window.location.replace为React Router的useNavigate钩子跳转,防止页面刷新导致Redux状态丢失
  • 注册成功后,若后端返回token,必须存入localStorage,保证后续接口请求能携带认证信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 19:17:12