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

Redux Toolkit中createAsyncThunk无法传递对象的问题求助

问题:向Redux Toolkit的createAsyncThunk传递参数时对象参数为undefined

在执行submitHandler函数时,尝试向createProductReview action传递两个参数:id以及包含rating和comment的对象,但该对象在reducer中打印显示为undefined,无法正确传递。

错误代码

submitHandler函数

const submitHandler = (e) => {
    e.preventDefault();
    dispatch(createProductReview({ id, { rating, comment } }));
};

createProductReview异步action

export const createProductReview = createAsyncThunk(
  'reviewProduct',
  async ({ productId, review }, thunkAPI) => {
    console.log(productId, review);
    try {
      const {
        userLogin: { userInfo },
      } = thunkAPI.getState();
      const config = {
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${userInfo.token}`,
        },
      };
      await axios.post(`/api/products/${productId}/reviews`, review, config);
    } catch (error) {
      const newError =
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message;
      return thunkAPI.rejectWithValue(newError);
    }
  }
);

错误原因

submitHandler中传递的对象存在语法错误:JavaScript对象字面量不允许直接嵌套未命名的对象({ id, { rating, comment } }这种写法非法),同时传递的键名和thunk中接收的productId、review不匹配,导致thunk无法正确解构到参数。

修正方案

  1. 修正submitHandler中的参数传递语法,给嵌套对象指定键名review,同时将id重命名为productId(和thunk接收的参数名对应):
const submitHandler = (e) => {
    e.preventDefault();
    dispatch(createProductReview({ 
      productId: id, 
      review: { rating, comment } 
    }));
};
  1. 确认thunk中的参数解构和传递的键名完全一致,这样就能正确获取到productId和review参数,不会出现undefined的情况。

错误截图说明

控制台报错Unexpected token '{',指向{ id, { rating, comment } }中的第二个大括号,说明该位置的对象字面量语法不符合JavaScript规范,这是导致参数无法传递的直接原因。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 00:35:20