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

createAsyncThunk多参数与getState使用报错:无法解构getState

解决createAsyncThunk中无法解构getState的问题

错误原因

createAsyncThunk的异步回调函数仅支持两个参数:

  • 第一个参数:调用thunk时传入的业务数据(payload)
  • 第二个参数:包含getState、dispatch等方法的thunkAPI对象

你写的async (teamId, comment, { getState })是错误的——第三个参数根本不存在,所以解构getState时会提示“未定义”。

正确解决方案

方案1:将多个参数打包为对象(推荐)

把teamId和comment放进一个对象作为payload传递,回调函数第一个参数解构这个对象,第二个参数取thunkAPI:

export const addTeamReview = createAsyncThunk(
  "team/addTeamReview",
  async ({ teamId, comment }, { getState }) => {
    const {
      userLogin: { userInfo },
    } = getState();

    try {
      await axios.post(`/api/teams/${teamId}/review`, comment, {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${userInfo.token}`,
        },
      });
    } catch (error) {
      console.log(error);
    }
  }
);

调用该thunk时,需传入对象:

addTeamReview({ teamId: "你的团队ID", comment: "你的评价内容" });

方案2:将多个参数打包为数组

如果习惯用数组传参,也可以把参数放进数组,回调函数第一个参数解构数组:

export const addTeamReview = createAsyncThunk(
  "team/addTeamReview",
  async ([teamId, comment], { getState }) => {
    const {
      userLogin: { userInfo },
    } = getState();

    try {
      await axios.post(`/api/teams/${teamId}/review`, comment, {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${userInfo.token}`,
        },
      });
    } catch (error) {
      console.log(error);
    }
  }
);

调用时传入数组:

addTeamReview(["你的团队ID", "你的评价内容"]);

为什么你之前的尝试无效?

  • 把getState放第二个参数、comment放第三个:不符合createAsyncThunk的参数结构,回调函数只能拿到前两个参数,第三个参数永远是undefined。
  • 打包对象后无效:大概率是调用thunk时没正确传入对象(比如还是分开传两个参数),或者回调里的解构逻辑有误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 16:35:12