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

使用Axios发起get请求时报Cannot read properties 'getState'错误求解

问题解决方案

首先报错Cannot read properties of undefined (reading 'getState')是多个原因共同导致的,按以下步骤修改即可修复:

1. 修正Redux Thunk异步Action的写法

你在Action中手动引入store的写法会触发循环依赖:store初始化完成前就被Action引入,导致获取到的store是undefined。Redux Thunk本身支持给异步Action传入getState参数,无需手动引入store,修改returnToWorkQuestion.action.js代码如下:

import axios from 'axios';
import {endpointURL} from '../../config/endpointConfig';

export const returnToWorkQuestions = (email, questionCategory) => {
  // thunk异步函数默认接收dispatch、getState两个参数
  return async (dispatch, getState) => {
    const state = getState();
    console.log('当前redux状态:', state);
    try {
      const response = await axios.get(`${endpointURL}getquestionnaire`, {
        params: {
          email: email,
          questionCategory: questionCategory,
        },
      });
      console.log('接口返回数据:', response);
      // 后续需要存储数据到redux时,在此处dispatch对应的reducer操作即可
    } catch (err) {
      console.error('请求报错:', err);
    }
  }
};

2. 补全Action调用的必填参数

你定义的returnToWorkQuestions需要传入email、questionCategory两个参数,Home.js中调用时没有传参会导致后续接口请求异常,修改调用逻辑:

// 先从redux中拿取存储的用户信息,替换成你实际的参数获取逻辑
const userInfo = useSelector(state => state.Authentication.user);
const dispatch = useDispatch();
const fetchReturntoWorkQuestion = () => {
  // 传入实际的email和问卷分类参数
  dispatch(returnToWorkQuestions(userInfo.email, 'returnWork'));
};

3. 可选后续配置

  • 如果后续需要将接口返回的问卷数据存储到Redux中,把rootStore.js中ReturnToWorkQuestions reducer的注册注释打开即可
  • 若仍需要手动引入store,注意rootStore.js中store是默认导出,引入时需要写成import store from '../rootStore',而非命名导入的写法

内容的提问来源于stack exchange,提问作者Daniel Döbereiner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:15:00