注册用户时触发Cannot read properties of undefined (reading 'user')错误求助
注册成功后Reducer报错"Cannot read properties of undefined (reading 'user')"的解决方案
问题现象
实现用户注册功能时,点击注册按钮后用户已成功注册,但前端弹出错误提示:
Cannot read properties of undefined (reading 'user')
错误发生在authSlice.js的userRegister.fulfilled处理逻辑中,相关错误日志及控制台信息如下:
错误日志
Uncaught runtime errors: ERROR `Cannot read properties of undefined (reading 'user') TypeError: Cannot read properties of undefined (reading 'user') at http://localhost:3000/static/js/bundle.js:1493:28 at http://localhost:3000/static/js/bundle.js:3065:20 at produce (http://localhost:3000/static/js/bundle.js:60637:17) at http://localhost:3000/static/js/bundle.js:3064:67 at Array.reduce (<anonymous>) at reducer (http://localhost:3000/static/js/bundle.js:3045:25) at reducer (http://localhost:3000/static/js/bundle.js:3146:14) at combination (http://localhost:3000/static/js/bundle.js:50634:29) at hu (<anonymous>:3:1043) at yu (<anonymous>:3:1331)
控制台错误
authSlice.js:36 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'user') at authSlice.js:36:1 at createReducer.ts:294:1 at produce (immerClass.ts:94:1) at createReducer.ts:293:1 at Array.reduce (<anonymous>) at reducer (createReducer.ts:260:1) at reducer (createSlice.ts:372:1) at combination (redux.js:560:1) at hu (<anonymous>:3:1043) at yu (<anonymous>:3:1331)
问题根源
查看authActions.js中的userRegister异步thunk:注册成功时,仅执行了页面跳转和提示,但没有将后端返回的data作为返回值传递给reducer,导致authSlice.js中userRegister.fulfilled的payload为undefined,此时访问payload.user就会触发上述错误。
后端authcontroller.js的注册接口已经正确返回了包含user字段的响应,但前端thunk未将该响应返回给reducer。
修复方案
修改authActions.js中的userRegister函数,在注册成功时返回后端返回的data,确保reducer能拿到完整的payload。
修改后的authActions.js代码
import {createAsyncThunk} from '@reduxjs/toolkit' import API from '../../../services/API'; import { toast } from 'react-toastify'; // ... 其他代码保持不变 export const userRegister= createAsyncThunk( 'auth/register', async ({name,role,email,password,organisationName,hospitalName,address,phone},{rejectWithValue})=>{ try { const {data}= await API.post('/auth/register',{name,role,email,password,organisationName,hospitalName,address,phone}) if(data?.success){ toast.success('用户注册成功'); window.location.replace('/login'); } // 关键:将后端返回的data返回给reducer return data; } catch (error) { console.log(error); if(error.response && error.response.data.message){ return rejectWithValue(error.response.data.message); }else{ return rejectWithValue(error.message) } } } )
可选增强(容错处理)
为了避免类似问题,可在authSlice.js的userRegister.fulfilled中增加payload存在性判断:
builder.addCase(userRegister.fulfilled,(state, {payload})=>{ state.loading=false; // 增加判断,避免payload为undefined时出错 if(payload?.user){ state.user=payload.user; } })
验证
修改代码后重新运行项目,点击注册按钮,用户成功注册后将不再出现错误提示,同时reducer能正确处理返回的用户数据。
内容的提问来源于stack exchange,提问作者Mrunal Kashid
相关产品推荐
相关产品推荐

