首页 > 解决方案 > `dispatch` 方法的类型签名不正确,尽管使用了“app dispatch”钩子

问题描述

介绍

我正在使用Redux Toolkit将 Redux 支持添加到由 Django 应用程序提供的 React 应用程序。我们正在使用 Typescript,因此我们遵循 Redux Toolkit 文档中的Typescript 快速入门

将 Redux (Toolkit?) 与 Typescript 一起使用的一个重要元素是确保您的dispatch(...)方法具有正确的类型签名。如文档中所述,如果您只是使用useDispatch(...)react-redux 中的钩子,

默认Dispatch类型不知道 thunk。为了正确调度 thunk,您需要使用AppDispatch商店中包含 thunk 中间件类型的特定自定义类型,并将其与useDispatch. 添加一个预先输入的useDispatch钩子可以防止你忘记AppDispatch在需要的地方导入。

没关系,我按照这些说明进行操作。我的代码导出了一个新的钩子,就像教程一样:

export type AppDispatch = typeof store.dispatch;
export const useAppDispatch = () => useDispatch<AppDispatch>();

我的问题是:当我使用那个钩子时,该dispatch(...)方法的类型签名仍然不接受 thunk。以下代码:

const dispatch = useAppDispatch();
dispatch(customAction({ ... params ... }));

产生编译错误:

ERROR in [at-loader] ./src/components/Widget.tsx:45:9 
TS2345: Argument of type 'AsyncThunkAction<void, CustomActionParams, {}>' is not assignable to parameter of type 'AnyAction'.
Property 'type' is missing in type 'AsyncThunkAction<void, CustomActionParams, {}>' but required in type 'AnyAction'.

我的问题:为什么键入的调度方法不能正确接受AsyncThunkActions?

我尝试过的事情

有趣的是,使用显式参数化dispatch(...)AppDispatch类型调用会导致相同的错误。只有参数化dispatch(...)可以any消除错误,这显然是不理想的。

const dispatch = useAppDispatch();
dispatch<AppDispatch>(customAction({ ... params ... })); // same error
dispatch<any>(customAction({ ... params ... })); // error silenced

这让我认为这个问题并AppDispatch没有正确地推断出它应该采用AsyncThunkAction类型,而这应该自动发生。可能导致这种情况的原因是我的异步操作是在 中定义extraReducers,如下所示:

export const customAction = createAsyncThunk(
    "slice/customAction",
    async (payload: CustomActionParams) { ... }
);

export const slice = createSlice({
    name: "slice",
    initialState,
    reducers: {},
    extraReducers: (builder) => {
         builder.addCase(customAction.fulfilled, (state, action) => { ... });
    }
});

我不确定为什么这不会导致类型更新,但这是我必须解决的问题。

与标准设置的差异

关于我的环境的一些事情在理论上也可能导致这个问题,所以为了正确起见,我将它们包括在这里:

重复的问题:

标签: reduxreact-reduxredux-thunkredux-toolkitthunk

解决方案


react-redux这个问题最终是由和@reduxjs/toolkit包之间的某种版本不匹配引起的。我删除了我的yarn.lock并删除了我的node_modules,然后从头开始重新安装,问题就消失了!

~4.1.5(此外,由于使用 Yarn 2 安装 TypeScript 的另一个问题,我还不得不将 TypeScript 固定在。)


推荐阅读