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

使用TypeScript的createAsyncThunk时遇rejectWithValue不是函数的TypeError

问题解决:createAsyncThunk中rejectWithValue报错"不是函数"

错误原因

你的代码错误地将rejectWithValue作为thunk函数的第二个参数直接传入,但实际上createAsyncThunk的回调函数第二个参数是一个thunkAPI对象,rejectWithValue是该对象的属性方法,而非独立参数。直接传入会导致rejectWithValue为undefined,从而触发类型错误。

修正后的代码

import { createAsyncThunk } from '@reduxjs/toolkit';
import type { AxiosResponse } from 'axios';

// 替换为你实际的类型定义
type LoginParam = { payload: object; callback: () => void };
type ApiResponseData = any; // 建议替换成接口定义的响应数据类型

export const loginUser = createAsyncThunk<ApiResponseData, LoginParam>(
  types.LOGIN_USER,
  async (param, { rejectWithValue }) => {
    try {
      const argum: apiArgs = {
        apiUrl: '/someurl',
        method: "POST",
        payload: param.payload
      };
      const response: AxiosResponse<ApiResponseData> = await apiCall(argum);
      param.callback();
      return response.data;
    } catch (err: any) {
      // 增加存在性判断,避免无response时的报错
      if (err.response?.data) {
        return rejectWithValue(err.response.data);
      }
      return rejectWithValue({ message: '请求失败' });
    }
  }
);

关键修正点

  • 参数解构:将第二个参数改为{ rejectWithValue },从thunkAPI对象中解构出该方法
  • TypeScript类型优化:
    • 显式指定createAsyncThunk的泛型参数:<成功返回数据类型, 传入参数类型>,提升类型校验能力
    • 为请求参数、响应数据定义明确类型(替换any为实际业务类型)
  • 错误处理增强:增加对err.response.data的存在性判断,避免网络错误等无response场景下的额外报错

修正后,请求失败进入catch块时,rejectWithValue会正确传递错误payload,你就能在reducer中通过action.payload获取到错误数据了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:40:39