Redux 工具包,缺少调度 thunk 类型

sup*_*r10 6 typescript reactjs redux redux-toolkit

我正在使用 redux-toolkit,并尝试发送一个 thunk。我正在使用的调度函数看起来像这样,这直接取自文档。eslint 抱怨缺少返回类型,知道它应该是什么吗?

export const useAppDispatch = () => useDispatch<AppDispatch>();
Run Code Online (Sandbox Code Playgroud)

此外,我得到了同样的错误,如这个问题How to split an Action or a ThunkAction (in TypeScript, with redux-thunk)? ,但据我了解,没有真正的解决方案。

所以如果我得到这样的代码:

export const fetchSomeThing = createAsyncThunk<SomeType[]>('someThing/fetch', async () => {
  const someClient = useSomeClient();
  const someThing: SomeType[] = await someClient.listSomething();
  return someThing;
});

// I also tried typing dispatch as AppDispatch here explicitly, but it gives me the same error
const dispatch = useAppDispatch();
dispatch(fetchSomeThing()) //This gives an error: Property 'type' is missing in type 'AsyncThunkAction<SomeType[], void, {}>' 
// but required in type 'AnyAction'.ts(2345), index.d.ts(21, 3): 'type' is declared here.
Run Code Online (Sandbox Code Playgroud)

我的商店是这样的:

export const store = configureStore({
  reducer: {
    someThing: someThingReducer,
  },
});

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch; // According to vs-code this is of type AppDispatch = Dispatch<AnyAction>
Run Code Online (Sandbox Code Playgroud)

phr*_*hry 7

最近,当人们以某种​​方式并行安装redux@4.0.5时,似乎会发生这种情况,并且通常可以通过执行或重新安装来解决。你能尝试一下吗?redux@4.1.0@types/react-reduxnpm i @types/react-reduxyarn add @types/react-redux

  • @Aleksas 我在使用 Yarn 2 时遇到了同样的问题。最终对我有用的是显式添加 `redux` 作为依赖项并确保 `@reduxjs/toolkit` 是最新的。如果您使用工作区,我能够使其正确键入的唯一方法是将“redux”添加到 _root_. 更多详细信息请参见:https://github.com/yarnpkg/berry/issues/3150 (2认同)