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

Redux Toolkit createAsyncThunk触发rejected时返回payload为空问题

createAsyncThunk rejected状态无法获取payload问题解决方案

问题原因

  • 参数结构错误:createAsyncThunk的 payload 构造函数仅接收2个参数,第一个是调用action时传入的自定义参数,第二个是完整的thunkAPI对象。你当前的写法async (data, { getState }, thunkAPI)错误将thunkAPI拆分为两个参数,导致代码中调用的thunkAPI实际为undefined,调用rejectWithValue会抛出额外异常,覆盖你预期返回的payload。
  • 取值路径错误:你调用rejectWithValue时传入的对象结构为{err: xxx, status: xxx}或{err: 'Network Error'},没有嵌套的data字段,但你在rejected reducer中取值路径为action.payload.data.error,自然无法取到对应值。
  • 语法错误:你贴出的reducer代码中多个对象属性末尾缺少逗号,也可能导致运行异常。

修复代码

修正异步action定义

export const action = createAsyncThunk(
  '/fullfilment/update-content-preference',
  // 修正参数结构,直接从thunkAPI中解构需要的方法
  async (data, { getState, rejectWithValue }) => {
    try {
      const state = getState();
      const authToken = state.auth.token;
      const { selectedShipmentId: shipmentId } = state.fullfilment;
      const obj = {
        ...data,
        shipmentId
      };
      const response = await axios.post(
        '/fullfilment/update-content-preference',
        obj,
        { headers: { Authorization: `Bearer ${authToken}` } }
      );
      return response;
    } catch (err) {
      if (err.response) {
        return rejectWithValue({
          err: err.response.data?.error || err.response,
          status: err.response.status,
          message: err.response.data?.message || '请求失败'
        });
      }
      return rejectWithValue({
        err: 'Network Error',
        message: '网络异常,请稍后重试'
      });
    }
  }
);

修正状态处理逻辑

[action.pending]: state => ({
    ...state,
    loading: true
  }),

  [action.fulfilled]: (state, action) => ({
    ...state,
    data: {
      ...state.data,
      loading: false,
      list: action.payload.data.list,
      message: action.payload.data.message
    }
  }),

  [action.rejected]: (state, action) => ({
    ...state,
    loading: false,
    // 修正取值路径,匹配rejectWithValue返回的结构
    error: action.payload.err,
    message: action.payload.message
  })

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:57:03