即使安装了 redux-thunk,dispatch 仍然期待一个 Action?

dispatch is still expecting an Action even when redux-thunk installed?

我正在尝试在基于 TypeScript 的 React Native 项目中使用 redux-thunk。我的操作定义为

export type Action<T> = {
  type: T,
  payload?: any
}

我的店铺定义为

import { applyMiddleware, createStore } from 'redux'
import { persistStore } from 'redux-persist'
import thunk from 'redux-thunk'

import logger from 'src/redux/middleware/logger'
import rootReducer from 'src/redux/reducers'

export const store = createStore(rootReducer, applyMiddleware(logger, thunk))
export const persistor = persistStore(store)

我的动作构造函数定义为

export const setRepeat = (repeat: Repeating) => (
  dispatch: Dispatch<Action>,
  getState: () => AppState
) =>
  dispatch<Action>({
    payload: repeat,
    type: actionTypes.SET_REPEAT,
  })

Repeating 是一个简单的枚举:

export enum Repeating {
  All = 'all',
  None = 'none',
  Single = 'single',
}

当我尝试使用

发送此操作时
store.dispatch(setRepeat('all' as Repeating))

我收到这个错误

TS2345: Property 'type' is missing in type '(dispatch: Dispatch<Action<string>>, getState: () => AppState) => Action<string>' but required in type 'Action<string>'.

据我所知,这意味着 setRepeat 正在返回一个函数(这是有道理的,这就是它定义的目的)。但是 store.dispatch 并不期待像 redux-thunk 允许的功能,并且仍然期待 Action.

我似乎找不到任何关于为什么 thunk 没有在这里提供正确类型的解释,或者我需要做什么来纠正这个问题。

This issue has been brought up on github

总而言之,您需要添加以下类型:

const store = createStore(
rootReducer,
applyMiddleware(
    thunk as ThunkMiddleware<IState, Actions>, // this is crucial
));

下面的原始答案

这里的问题是 dispatch 接受了一个 Action<T> 的类型,它有一个 属性 type 但你向它发送了一个函数,而函数没有有类型。请注意 setRepeat 是 returns 另一个函数的函数。

store.dispatch(setRepeat('all' as Repeating)(dispatcherInstance,getStateFunction))

我需要查看更多您的代码,但您的做法似乎有点不对。