移动端浏览器登录后Redux auth状态置空致Me接口401错误
移动端登录后Redux auth状态重置导致401错误
Web应用桌面端登录功能正常,但部分移动端浏览器登录时出现异常:调用Login接口成功跳转到Dashboard页面后,调用获取用户信息的Me接口返回401错误。通过Redux控制台观察到,登录后会触发两次reset操作,导致登录获取的用户信息被清空,进而引发请求无有效凭证的问题。
以下是相关代码片段:
authSlice代码
export const authSlice = createSlice({ name: "auth", initialState, reducers: { reset: (state) => initialState }, extraReducers:(builder) => { builder.addCase(LoginUser.pending, (state) => { state.isLoading = true }); builder.addCase(LoginUser.fulfilled, (state, action) => { state.isLoading = true; state.isSuccess = true; state.user = action.payload; }); builder.addCase(LoginUser.rejected, (state, action) => { state.isLoading = false; state.isError = true; state.message = action.payload }) // Get UserLogin builder.addCase(getMe.pending, (state /*action*/) => { state.isLoading = true; //state.user = action.payload; }); builder.addCase(getMe.fulfilled, (state, action) => { state.isLoading = true; state.isSuccess = true; state.user = action.payload; }); builder.addCase(getMe.rejected, (state, action) => { state.isLoading = false; state.isError = true; state.message = action.payload }) } }); export const { reset } = authSlice.actions; export default authSlice.reducer;
LoginUser异步逻辑
export const LoginUser = createAsyncThunk("user/LoginUser", async(user, thunkAPI) => { try { const response = await axios.post('https://app-cool/login', { email: user.email, password: user.password }) for (const key in response.data) { if (response.data.hasOwnProperty.call(response.data, key)) { const element = DOMPurify.sanitize(response.data[key]); response.data[key] = element; } } return response.data; } catch (error) { if(error.response){ const message = error.response.data.msg return thunkAPI.rejectWithValue(message); } } })
getMe异步逻辑
export const getMe = createAsyncThunk("user/getMe", async(_, thunkAPLI) => { try { const response = await axios.get('https://app-cool/Me') const data = response.data for (const key in data) { if (data.hasOwnProperty.call(data, key)) { if(key !== 'empresa'){ const element = DOMPurify.sanitize(data[key]); data[key] = element; } } } return(response.data); })
登录页面逻辑
const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const dispatch = useDispatch(); const navigate = useNavigate(); const { user, isError, isSuccess, isLoading, message } = useSelector( (state) => state.auth ); useEffect(() => { if(user || isSuccess){ navigate("/dashboard") } dispatch(reset()); }, [user, isSuccess, dispatch, navigate]) const Auth = (e) =>{ e.preventDefault(); dispatch(LoginUser({email, password})); }
Dashboard页面逻辑
const { user } = useSelector((state) => state.auth); const [votaciones, setVotaciones] = useState([]); let votaciones_validas = []; useEffect(() => { if(user && user.empresa){ setVotaciones(user.empresa.votacions); } }, [user]);
问题根源
登录页面的useEffect存在逻辑缺陷:无论登录状态如何变化,每次触发都会无条件调用dispatch(reset())。在移动端浏览器中,页面跳转后的组件生命周期行为与桌面端存在差异,导致这个useEffect被触发两次:
- 第一次:
LoginUser.fulfilled更新user和isSuccess,触发useEffect跳转到Dashboard,同时调用reset()清空状态; - 第二次:登录页面组件未立即卸载,或状态变化再次触发
useEffect,再次执行reset()彻底清除auth状态;
此时Dashboard调用getMe接口时,Redux中已无用户信息,请求缺少有效凭证,返回401错误。
修复方案
1. 修正登录页面的useEffect逻辑
仅在登录成功或出错时重置状态,避免无条件清空用户信息:
useEffect(() => { if(user || isSuccess){ navigate("/dashboard"); // 登录成功后重置状态,避免残留状态影响后续操作 dispatch(reset()); } // 登录失败时重置错误状态 if(isError){ dispatch(reset()); } }, [user, isSuccess, isError, dispatch, navigate])
2. 修正authSlice中的状态错误
LoginUser.fulfilled和getMe.fulfilled中错误地将isLoading设为true,登录/获取用户信息成功后应改为false:
// 修正LoginUser.fulfilled builder.addCase(LoginUser.fulfilled, (state, action) => { state.isLoading = false; state.isSuccess = true; state.user = action.payload; }); // 修正getMe.fulfilled builder.addCase(getMe.fulfilled, (state, action) => { state.isLoading = false; state.isSuccess = true; state.user = action.payload; });
3. 补全getMe的异常处理逻辑
原代码缺少catch块的完整实现,导致异步操作出错时无法正确处理:
export const getMe = createAsyncThunk("user/getMe", async(_, thunkAPI) => { try { const response = await axios.get('https://app-cool/Me') const data = response.data for (const key in data) { if (data.hasOwnProperty.call(data, key)) { if(key !== 'empresa'){ const element = DOMPurify.sanitize(data[key]); data[key] = element; } } } return(response.data); } catch (error) { if(error.response){ const message = error.response.data.msg return thunkAPI.rejectWithValue(message); } } })
内容的提问来源于stack exchange,提问作者Enrique Espinosa
相关产品推荐
相关产品推荐

