首页 > 解决方案 > 类型“ThunkAction”上不存在属性“then”

问题描述

我收到错误

Property 'then' does not exist on type 'ThunkAction<Promise<string>

我正在尝试从我的切片中的 AppThunk 返回一个承诺。

下面是我设置的代码,我经历了几个相同的问题,并遵循了那里给出的一些建议,但仍然无法弄清楚出了什么问题。

store.ts

import { configureStore, Action } from '@reduxjs/toolkit'
import { useDispatch } from 'react-redux'
import { ThunkAction } from 'redux-thunk'

import rootReducer, { RootState } from './rootReducer'

const store = configureStore({
  reducer: rootReducer
})

if (process.env.NODE_ENV === 'development' && module.hot) {
  module.hot.accept('./rootReducer', () => {
    const newRootReducer = require('./rootReducer').default
    store.replaceReducer(newRootReducer)
  })
}

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


export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string>
>

export default store

我的切片.ts

import { AppThunk } from 'app/store'

// ...
// my reducer logic is here 
// ...

export const fetchIssuePromise = (): AppThunk<Promise<string>> => async (dispatch) => {
  return Promise.resolve("string")
}

我在我的组件中使用它。

我的组件.tsx

import React, { useEffect } from 'react'
import { fetchIssue, fetchIssuePromise } from 'features/mySlice.ts'
import {  useDispatch } from 'react-redux'

export const MyComponent = ({
const dispatch = useDispatch()

useEffect(() => {
      dispatch(fetchIssuePromise()).then(() => {
      // My logic here.
      })
  }, [dispatch])
  
  
})

我知道我可以通过存储在 redux 状态并使用选择器来实现这一点。但我不想在 redux 中存储一些数据,尤其是来自服务器的验证错误。

我不确定这种方法是否正确,请让我知道如何处理此问题或任何更好的方法来实现此目标。

标签: reactjstypescriptreact-reduxtypescript-typingsredux-thunk

解决方案


不要使用默认的“useDispatch”钩子。

正如这个 github 问题中提到的:https ://github.com/reduxjs/redux-toolkit/issues/678

链接文档:https ://redux-toolkit.js.org/usage/usage-with-typescript#getting-the-dispatch-type

在您的 store.ts 中:

    export type RootState = ReturnType<typeof store.getState>
    export type AppDispatch = typeof store.dispatch
    export const useAppDispatch = () => useDispatch<AppDispatch>()

在您的 Component.tsx 中:

    const dispatch = useAppDispatch() // hook exported from store

推荐阅读