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

MERN栈报错Path `comment` is required,请求排查原因

排查Path comment is required错误

核心问题出在Redux Toolkit的createAsyncThunk参数处理上,导致前端没有把包含comment的review对象正确传递给后端。

错误原因

在addProductReview这个异步Thunk中,你错误理解了createAsyncThunk的参数结构:

  • createAsyncThunk的payloadCreator函数(第二个参数),第一个参数是dispatch时传入的唯一payload参数,第二个参数是ThunkAPI对象(包含dispatch、getState等属性,并没有review字段)。
  • 你现在dispatch时传入了id和review两个参数,但payloadCreator只能拿到第一个参数id,解构出的{review}是undefined,最终axios发送给后端的请求体是undefined,后端自然找不到comment字段,触发验证错误。

修正方案

方案一:合并参数为一个对象传递

1. 修改页面提交的dispatch代码

const submitHandler = e => {
  e.preventDefault();
  dispatch(
    addProductReview({
      productId: id,
      reviewData: {
        rating,
        comment,
      },
    })
  );
};

2. 修改productSlice中的异步Thunk代码

export const addProductReview = createAsyncThunk(
  'product/review',
  async ({ productId, reviewData }, thunkAPI) => {
    try {
      const { data } = await axios.post(
        `/api/v1/products/${productId}/reviews`,
        reviewData
      );
      return data;
    } catch (error) {
      const message = error.response.data.msg;
      return thunkAPI.rejectWithValue(message);
    }
  }
);

方案二:用数组打包多参数传递

1. 修改页面的dispatch调用

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

2. 修改productSlice中的异步Thunk代码

export const addProductReview = createAsyncThunk(
  'product/review',
  async ([id, review], thunkAPI) => {
    try {
      const { data } = await axios.post(
        `/api/v1/products/${id}/reviews`,
        review
      );
      return data;
    } catch (error) {
      const message = error.response.data.msg;
      return thunkAPI.rejectWithValue(message);
    }
  }
);

额外检查点

确认你的Product模型Schema中,reviews数组里的comment字段确实设置为required: true,如果是,只要前端正确传递数据,错误就会消失。

内容的提问来源于stack exchange,提问作者Uros Dioda Rakic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 00:20:38