“AsyncThunkAction”类型的 Redux-toolkit 上不存在属性“then”

IT技术 reactjs redux redux-thunk redux-toolkit
2021-05-10 16:30:17

我似乎无法 我对 Typescript 相当陌生的人那里收到PromisefromcreateAsyncThunk函数Redux-toolkit,我正在努力弄清楚为什么它会给我 Property 'then' does not exist on type 'AsyncThunkAction<Student, number, {}>'错误,即使如果我删除打字,Promise确实会返回。这是我的createAsyncThunkfn

export const getStudentByIdRequest = createAsyncThunk<Student, number>(
  'student/getStudentByIdRequest',
  async (id, { rejectWithValue }) => {
    try {
      const { data } = await instance.get(`student/${id}/`)
      return data
    } catch (err) {
      let error: AxiosError = err
      if (error) {
        return rejectWithValue({
          message: `Error. Error code ${error.response?.status}`,
        })
      }
      throw err
    }
  }
)

这就是我从React组件中发送它的方式

dispatch(getStudentByIdRequest(userId)).then((res) => console.log(res))

错误出现在我尝试调用thenthunk 的地方

2个回答

dispatch没有考虑 thunk 的类型,因此返回类型的类型不正确。请使用文档中描述Dispatch的商店中的实际类型

import { configureStore } from '@reduxjs/toolkit'
import { useDispatch } from 'react-redux'
import rootReducer from './rootReducer'

const store = configureStore({
  reducer: rootReducer
})

export type AppDispatch = typeof store.dispatch
export const useAppDispatch = () => useDispatch<AppDispatch>() // Export a hook that can be reused to resolve types

然后在您的组件中使用useAppDispatch而不是useDispatch

另一个可能的解决方案是使用ThunkDispatchtype 而不是 plain Dispatch,因为 plainDispatch并不意味着处理异步内容。

useAppThunkDispatch在 store.ts 中定义可重用钩子:

import { Action, ThunkDispatch, configureStore } from '@reduxjs/toolkit';

export const store = configureStore({
    reducer: {
        blog: blogSlice,
    },
});

export type RootState = ReturnType<typeof store.getState>;

export type ThunkAppDispatch = ThunkDispatch<RootState, void, Action>;

export const useAppThunkDispatch = () => useDispatch<ThunkAppDispatch>();

然后你可以useAppThunkDispatch在你的应用程序中使用钩子,就像useAppDispatchuseDispatch钩子一样。