" Error: Before running a Saga, you must mount the Saga middleware on the Store using applyMiddleware "

" Error: Before running a Saga, you must mount the Saga middleware on the Store using applyMiddleware "

如何使用 redux store 配置 redux saga,我已经试过了,但我在顶部遇到了这个错误“

import React from "react" import { Provider } from "react-redux" 
import { createStore as reduxCreateStore, applyMiddleware } from "redux" 
import createSagaMiddleware from "redux-saga" 
import "regenerator-runtime/runtime" 
import rootReducer from "./reducers" 
import sagas from "./sagas"

const sagaMiddleware = createSagaMiddleware() 
const createStore = () =>  reduxCreateStore(
    rootReducer,
    applyMiddleware(sagaMiddleware),
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()   )

sagaMiddleware.run(sagas);

export default ({ element }) => (   <Provider store={createStore()}>{element}</Provider> )

如错误所述,您在创建商店之前调用 sagaMiddleware.run。在上面的行中,您创建了一个最终创建商店的函数(一旦它在 React 组件中被调用),但这只会在您尝试 运行 中间件之后发生,但为时已晚。

根据您的需要,这个问题有两种解决方案。

a) 要么摆脱工厂,然后立即创建商店。

const sagaMiddleware = createSagaMiddleware() 
const store = reduxCreateStore( // notice the missing () =>
    rootReducer,
    applyMiddleware(sagaMiddleware),
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()   )

sagaMiddleware.run(sagas);

export default ({ element }) => (   <Provider store={store}>{element}</Provider> )

b) 将中间件逻辑移动到创建存储函数中

const createStore = () => {
    const sagaMiddleware = createSagaMiddleware() 
    reduxCreateStore(
        rootReducer,
        applyMiddleware(sagaMiddleware),
        window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
    )
    sagaMiddleware.run(sagas);
    return store;
}

export default ({ element }) => (   <Provider store={createStore()}>{element}</Provider> )

除非有特殊原因需要工厂,否则我会推荐第一个。