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

向带类型的CreatedAsyncThunk通过thunkApi传dispatch触发参数报错如何解决?

问题原因与解决方案

核心错误点

  • createAsyncThunk 泛型参数顺序填写错误
    createAsyncThunk 的泛型定义顺序为 <*返回值类型*, *调用thunk时传入的参数类型*, *ThunkApi配置类型*>,你把原本应该放在第三位的ThunkApi类型声明错放到了第二位,导致TS认为调用这个thunk时必须传入一个包含dispatch的对象,所以触发了缺少参数的报错。
  • payload creator 函数参数顺序错误
    payload creator的第一个参数是调用thunk时传入的实参,第二个参数才是thunkApi对象,你之前把thunkApi写到第一个参数位,即使传参也无法正常获取dispatch方法。
  • 返回值类型不匹配
    你声明的返回值类型是Device[],但代码里返回{ ...devices }会把数组展开为普通对象,和声明的数组类型不匹配,运行时也会得到错误的数据结构。

修正后的代码

deviceOperations.ts

import { createAsyncThunk } from '@reduxjs/toolkit';
import { AppDispatch, RootState } from 'src/store';
import { loaderActions } from '../../../features/loader/redux';
import deviceManager from '../deviceManager';

export const getAllDevices = createAsyncThunk<
  Device[], // 第一位:thunk执行成功的返回值类型
  void, // 第二位:调用thunk时不需要传参,填void即可
  { // 第三位:ThunkApi的类型声明
    dispatch: AppDispatch;
    state: RootState;
  }
>('device/GET_ALL_DEVICES', async (_, thunkApi) => {
  // 不需要入参所以第一个参数用_占位,第二个参数取thunkApi
  thunkApi.dispatch(loaderActions.start('getAllDevices'));
  try {
    const devices = await deviceManager.getAllDevices();
    return devices; // 直接返回数组,匹配声明的Device[]类型
  } finally {
    thunkApi.dispatch(loaderActions.stop('getAllDevices'));
  }
});

DevicePage.tsx

原有调用代码不需要修改,因为我们把第二位泛型设为了void,调用时不需要传任何参数:

const DevicePage = () => {
  const classes = useStyles();
  const dispatch = useAppDispatch();
  const { push } = useHistory();

  useEffect(() => {
    dispatch(deviceOperations.getAllDevices());
  }, [dispatch]);
};

内容的提问来源于stack exchange,提问作者juliano.net

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 07:06:04