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

TypeScript中如何在一个thunk函数内部执行另一个thunk函数

问题本质

默认的Redux Dispatch 类型仅支持接收普通纯对象action,无法识别thunk函数类型的入参,因此在thunk内部调用另一个thunk时会触发类型报错。

通用解决方案

核心是给Dispatch扩展thunk支持的类型定义,分两种场景对应实现:

场景1:原生Redux + redux-thunk 配置

  • 第一步:定义扩展后的Dispatch类型
import { ThunkDispatch } from 'redux-thunk';
import { AnyAction } from 'redux';
// 替换为你项目中RootState的实际定义路径
import { RootState } from './store/rootReducer';

// 支持thunk的Dispatch类型,可全局复用
export type AppThunkDispatch = ThunkDispatch<RootState, unknown, AnyAction>;
  • 第二步:给thunk函数的dispatch参数指定上述扩展类型
// 错误示例:使用默认Dispatch类型
const login = (userInfo: UserInfo) => async (dispatch: Dispatch) => {
  dispatch(authSuccess(userInfo));
  // 此处报错:默认Dispatch不接受thunk函数作为参数
  dispatch(logoutTimeout(3600)); 
}

// 正确示例:使用扩展后的AppThunkDispatch类型
const login = (userInfo: UserInfo) => async (dispatch: AppThunkDispatch) => {
  dispatch(authSuccess(userInfo));
  // 可正常调用任意thunk函数,无类型报错
  dispatch(logoutTimeout(3600)); 
}

场景2:Redux Toolkit 配置(更简便)

Redux Toolkit默认集成redux-thunk,无需额外安装依赖,直接导出store自带的Dispatch类型即可:

  • 第一步:在store入口文件导出类型
import { configureStore } from '@reduxjs/toolkit';
import rootReducer from './reducers';

export const store = configureStore({
  reducer: rootReducer
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
  • 第二步:全局封装自定义Hook,组件和thunk中均可复用
import { useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from './store';

// 组件中直接调用useAppDispatch即可获得支持thunk的dispatch实例
export const useAppDispatch = useDispatch.withTypes<AppDispatch>();
export const useAppSelector = useSelector.withTypes<RootState>();

在thunk函数中直接指定dispatch类型为AppDispatch即可正常调用所有thunk函数,和场景1用法一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:15:08