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

React Redux问题:从Store获取的accountInfo对象为空

解决Redux中获取账户信息accountInfo为空的问题

问题根源

你的getAccountInfo是同步Action Creator,但内部的fetch是异步操作。当函数返回Action对象时,异步请求还未完成,accountInfo仍为初始空对象,导致Reducer接收到的payload为空。此外,dispatch后立刻调用store.getState()也会因为Redux状态更新的异步性,打印出旧的状态值。

解决方案

需要使用Redux Thunk中间件处理异步Action,确保在请求完成后再分发Action更新状态。

1. 确保项目已配置Redux Thunk

如果还未安装,先执行:

npm install redux-thunk

创建Store时应用中间件:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const store = createStore(rootReducer, applyMiddleware(thunk));

2. 修改getAccountInfo为异步Action Creator

export const getAccountInfo = () => async (dispatch) => {
    try {
        const token = localStorage.jwtToken;
        setAuthToken(token);

        const decoded = jwt_decode(token);
        const currentUsername = decoded.name;
        const res = await fetch(`${Globals.API_URL}/account/info/?username=${currentUsername}`, { 
            headers: { "x-access-token": token }
        });
        const data = await res.json();

        let accountInfo = data.message != null 
            ? { message: data.message } 
            : data;

        dispatch({
            type: "GET_ACCOUNT_INFO",
            payload: accountInfo
        });
    } catch (error) {
        dispatch({
            type: "GET_ACCOUNT_INFO",
            payload: { error: error.message }
        });
    }
}

3. 调整状态获取逻辑

由于异步Action返回Promise,可使用async/await等待请求完成后再获取状态:

// 将外层代码包裹在async函数中
if (localStorage.jwtToken) {
  const token = localStorage.jwtToken;
  setAuthToken(token);
  const decoded = jwt_decode(token);
  store.dispatch(setCurrentUser(decoded));
  const currentTime = Date.now() / 1000;
  if (decoded.exp < currentTime) {
    store.dispatch(logoutUser());
  } else {
    await store.dispatch(getAccountInfo());
    console.log(store.getState());
    loggedIn = true;
  }
}

补充说明

如果是在React组件中,更推荐使用useSelector钩子实时获取最新状态,而不是直接调用store.getState():

import { useSelector } from 'react-redux';

// 组件内部
const accountInfo = useSelector(state => state.account.accountInfo);

内容的提问来源于stack exchange,提问作者Bradley A.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 12:43:18