React Native调用redux thunk异步action报'then不存在'TS错误如何解决
问题原因与解决方案
关于js和tsx混合使用的疑问
混合使用tsx和js文件不是导致报错的直接原因,两个报错均属于TypeScript类型校验规则触发的问题,和文件类型混用无关。
第一个报错解决:Property 'then' does not exist on type '(dispatch: any) => Promise<void>'.ts(2339)
报错原因
你当前使用的dispatch是Redux默认的普通Dispatch类型,默认无法识别redux-thunk异步Action返回的Promise,因此找不到then方法。
解决步骤
- 若未安装redux-thunk类型依赖,先执行安装:
npm i @types/redux-thunk -D
- 给你的Redux Store配置全局类型,你可以选择将store.js改为store.ts,或者同目录下新增
store.d.ts类型声明文件,添加如下类型定义:
import type { ThunkDispatch } from 'redux-thunk'; import type { AnyAction } from 'redux'; // 全局根状态类型,后续useSelector也会用到 export type RootState = ReturnType<typeof rootReducer> // 支持thunk异步操作的Dispatch类型 export type AppDispatch = ThunkDispatch<RootState, any, AnyAction>
- 在Register.tsx中使用自定义的AppDispatch类型替代默认Dispatch:
如果你是通过useDispatchhook获取dispatch,修改写法如下:
import { useDispatch } from 'react-redux'; import type { AppDispatch } from '你的store文件路径'; // 组件内部获取dispatch const dispatch = useDispatch<AppDispatch>();
修改完成后dispatch就能识别异步Action返回的Promise,then方法报错会消失。
第二个报错解决:Parameter 'err' implicitly has an 'any' type.ts(7006)
报错原因
TypeScript默认开启了不允许隐式any类型的校验规则,你没有给catch的err参数声明类型,因此触发报错。
解决方法(二选一即可,推荐第一种)
- 方法1:给err参数显式声明类型,通用写法如下:
.catch((err: Error) => console.log(err));
如果你的接口返回的错误有固定格式,也可以自定义错误类型替换Error。
- 方法2:关闭隐式any校验规则,在项目根目录的
tsconfig.json中,修改compilerOptions配置:
{ "compilerOptions": { "noImplicitAny": false } }
内容的提问来源于stack exchange,提问作者user15088424
相关产品推荐
相关产品推荐

