Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

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

How to configuring redux saga with redux store, i've tried this but i get this error which along top "

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> )

question from:https://stackoverflow.com/questions/65845984/error-before-running-a-saga-you-must-mount-the-saga-middleware-on-the-store

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As the error says, you are calling sagaMiddleware.run before the store is created. On the line above you create a function that eventually creates the store (once it's called in the react component), but that happens only after you try to run the middleware which is too late.

There are two solutions to this problem depending on your needs.

a) Either get rid of the factory and just create the store immediately.

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) Move the middleware logic into the create store function

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> )

I would recommend the first one unless there is a particular reason why you need the factory instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...