store.dispatch调用Redux Saga异步Action报TS类型错误如何解决?
问题解决:store.dispatch调用Saga异步Action报类型不匹配
报错原因
你的TypeScript类型定义中,用于约束dispatch入参的RootAction联合类型,仅包含了reducer会处理的同步Action(IncrementAction、DecrementAction),没有将Saga监听的异步Action(IncrementAsyncAction)加入联合类型,导致dispatch传入异步Action时触发类型不匹配报错:
Argument of type 'IncrementAsyncAction' is not assignable to parameter of type 'IncrementAction | DecrementAction'. Type 'IncrementAsyncAction' is not assignable to type 'DecrementAction'. Types of property 'type' are incompatible. Type "INCREMENT_ASYNC" is not assignable to type "DECREMENT".ts(2345)
而useDispatch没有触发报错的原因是你没有给它指定严格的泛型约束,默认的Dispatch类型允许传入任意结构的Action,属于类型宽松的效果,并非真正的类型适配。
解决步骤
1. 扩展RootAction联合类型
将所有Saga用到的异步Action类型,加入到原有的RootAction联合类型中:
// 修改前 // type RootAction = IncrementAction | DecrementAction; // 修改后 type RootAction = IncrementAction | DecrementAction | IncrementAsyncAction; // 如果有其他异步Action,全部依次加入即可
2. 给store.dispatch绑定正确类型
创建store时,关联上扩展后的RootAction类型,或者自定义项目通用的Dispatch类型:
import { createStore, applyMiddleware } from 'redux'; import createSagaMiddleware from 'redux-saga'; import rootReducer from './reducer'; import rootSaga from './saga'; const sagaMiddleware = createSagaMiddleware(); const store = createStore(rootReducer, applyMiddleware(sagaMiddleware)); sagaMiddleware.run(rootSaga); // 定义项目通用的Dispatch类型 export type AppDispatch = typeof store.dispatch; // 也可以显式指定入参类型: // export type AppDispatch = (action: RootAction) => RootAction;
3. (可选)给useDispatch也添加泛型约束
为了保证组件内调用dispatch也有严格的类型检查,建议给useDispatch指定上面定义的AppDispatch类型:
import { useDispatch } from 'react-redux'; import type { AppDispatch } from './store'; // 组件内调用 const dispatch = useDispatch<AppDispatch>();
不推荐的临时方案
如果不想调整类型定义,可以临时用类型断言跳过检查,会丢失类型校验能力,仅建议调试时使用:
store.dispatch(incrementAsync() as any);
内容的提问来源于stack exchange,提问作者hayaoki hayane
相关产品推荐
相关产品推荐

