Redux dispatch触发异步action报类型错误如何解决
注:问题描述中提到的
getIncidents(id)和示例代码里的getOrders(id)命名不一致,属于笔误,以下修复方案针对代码中实际定义的getOrders异步逻辑。
报错原因
这个TS错误是类型不匹配导致的:
- 你编写的
getOrders是Redux Thunk异步逻辑,返回值是(dispatch) => Promise<void>格式的函数,不是带type属性的普通action对象 - 直接从
react-redux引入的useDispatch默认返回的dispatch类型,仅支持接收普通同步action对象,没有包含thunk中间件扩展的函数类型支持,因此类型校验时判定传入参数不符合要求。
修复方案
根据你项目使用的Redux技术栈选对应方案即可:
方案1:使用Redux Toolkit(RTK,官方推荐方案)
RTK默认内置redux-thunk支持,只要导出正确的类型化dispatch钩子就能解决问题:
- 在store配置文件中导出store对应的类型:
// store.ts import { configureStore } from '@reduxjs/toolkit' // 引入你的业务reducer const store = configureStore({ reducer: { // 填写你的reducer配置 } }) export type RootState = ReturnType<typeof store.getState> export type AppDispatch = typeof store.dispatch export default store
- 封装带类型的自定义dispatch钩子,替代原生
useDispatch:
// app/hooks.ts import { useDispatch } from 'react-redux' import type { AppDispatch } from './store' export const useAppDispatch: () => AppDispatch = useDispatch
- 组件中替换为自定义钩子调用即可:
// someComponent.ts import { useAppDispatch } from './hooks' // 其他组件逻辑 const dispatch = useAppDispatch() useEffect(() => { dispatch(getOrders(id)) // 类型校验正常通过 }, [dispatch, id])
方案2:原生Redux手动挂载thunk的老项目
如果项目没有使用RTK,是手动通过createStore+applyMiddleware挂载thunk的场景,手动给dispatch补充thunk类型即可:
- 先确认store已经正确挂载thunk中间件,否则运行时也会执行失败:
// store.ts import { createStore, applyMiddleware } from 'redux' import thunk from 'redux-thunk' import rootReducer from './reducers' const store = createStore( rootReducer, applyMiddleware(thunk) // 必须挂载thunk中间件才能处理函数形式的action ) export default store
- 组件中声明dispatch时指定ThunkDispatch类型:
import { useDispatch } from 'react-redux' import { ThunkDispatch } from 'redux-thunk' import { AnyAction } from 'redux' // 组件内 const dispatch = useDispatch<ThunkDispatch<unknown, unknown, AnyAction>>() useEffect(() => { dispatch(getOrders(id)) // 类型校验通过 }, [dispatch, id])
临时快速修复可以直接在调用时加类型断言:
dispatch(getOrders(id) as AnyAction),但不推荐长期使用,会丢失thunk的类型推导。
内容的提问来源于stack exchange,提问作者BeginnerDev
相关产品推荐
相关产品推荐

