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无法正确解构到参数。
修正方案
- 修正
submitHandler中的参数传递语法,给嵌套对象指定键名review,同时将id重命名为productId(和thunk接收的参数名对应):
const submitHandler = (e) => { e.preventDefault(); dispatch(createProductReview({ productId: id, review: { rating, comment } })); };
- 确认thunk中的参数解构和传递的键名完全一致,这样就能正确获取到
productId和review参数,不会出现undefined的情况。
错误截图说明
控制台报错Unexpected token '{',指向{ id, { rating, comment } }中的第二个大括号,说明该位置的对象字面量语法不符合JavaScript规范,这是导致参数无法传递的直接原因。
内容的提问来源于stack exchange,提问作者Usama BG
相关产品推荐
相关产品推荐

