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

React-Thunk+Redux登出时getState()获取状态属性为undefined问题求助

问题分析与解决方案

嘿,你完全可以在异步thunk函数里调用getState(),问题根本不在异步调用本身!我一眼就看到了问题的核心——你没有正确访问合并后的Redux根状态结构。

问题原因

你用combineReducers({ systemState })把SystemStateReducer挂载到了根状态的systemState属性下,这意味着你的Redux根状态结构是这样的:

{
  systemState: {
    isLogined: boolean,
    user?: User,
    errorMessage?: string
  }
}

而你当前的代码直接从根状态里解构user和isLogined:

const { user, isLogined } = getState();

这相当于在根状态对象里找这两个字段,但根状态里只有systemState这个属性,所以自然会拿到undefined。

修正后的登出函数

只需要调整一下状态的访问路径,先拿到systemState属性,再解构里面的字段:

function logout() : ThunkAction<void, SystemState, null, Action<string>> {
  return async (dispatch, getState) => {
    // 先获取根状态里的systemState,再解构需要的字段
    const { systemState: { user, isLogined } } = getState();
    console.log(`user: ${user} isLogined:${isLogined}` )
    
    if (!isLogined) {
      dispatch(actions.LogoutFailed("No login Session Found"));
    } else if (user) {
      const result = await services.Logout(user.UserId);
      if (result.errorMessage) {
        dispatch(actions.LogoutFailed(result.errorMessage));
      } else {
        dispatch(actions.Logout());
      }
    }
  }
}

或者你也可以分步获取,逻辑更清晰:

const rootState = getState();
const { user, isLogined } = rootState.systemState;

额外小建议

你的SystemState初始状态里最好补上user和errorMessage的默认值,让状态结构始终保持一致,避免后续可能出现的隐性问题:

const initState = { 
  isLogined: false,
  user: undefined,
  errorMessage: undefined
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 06:35:08