“AsyncThunkAction"类型的 Redux-toolkit 上不存在属性“then" [英] Property 'then' does not exist on type 'AsyncThunkAction' Redux-toolkit
问题描述
我似乎无法从 Redux-toolkit
的 createAsyncThunk
函数接收到 Promise
我对打字稿相当陌生,我正在努力弄清楚为什么它会给我属性 'then' 在类型 'AsyncThunkAction
错误中不存在,即使我删除输入后会返回承诺.这是我的 createAsyncThunk
f-n
I can't seem to receive a Promise
from createAsyncThunk
function from Redux-toolkit
I'm fairly new to Typescript and I'm struggling to figure out why it's giving me
Property 'then' does not exist on type 'AsyncThunkAction<Student, number, {}>'
error even though the promise does get returned if I remove the typing.
Here is my createAsyncThunk
f-n
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
组件发送它的方式
And that is how I dispatch it from my React
component
dispatch(getStudentByIdRequest(userId)).then((res) => console.log(res))
我尝试在 thunk 上调用 then
时出现错误
The error appears where I try to call then
on the thunk
推荐答案
您的 dispatch
没有考虑 thunk 的类型,因此返回类型的类型不正确.请使用商店中的实际 Dispatch
类型,如 文档:
Your dispatch
does not take types for thunks into account and thus the return type is typed incorrectly. Please use the actual Dispatch
type from the store as decsribed in the documentation:
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
.
and then use useAppDispatch
instead of useDispatch
in your component.
这篇关于“AsyncThunkAction"类型的 Redux-toolkit 上不存在属性“then"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!