Redux-Saga报错:saga参数必须是生成器函数的排查与解决
Hey there! Let's break down exactly what's going on here—you ran into a super common Redux Saga gotcha, but you already found the fix, so let's connect the dots to make sure you understand why it worked.
1. First, Let's Talk About Your saga.mock.js
Your saga file exports a Generator function (function* taskCreationSaga()), which is non-negotiable for Redux Saga. Generators let Saga pause and resume execution, which is how it handles listening for actions, waiting on async operations, and dispatching new actions.
Inside that infinite while (true) loop, yield take(mutations.REQUEST_TASK_CREATION) tells the saga: "Pause here until someone dispatches the REQUEST_TASK_CREATION action, then grab the groupID from that action and keep going."
2. Why Your Initial Code Threw That Error
Looking at your store setup:
import * as sagas from './sagas.mock' // ... for (let saga in sagas) { sagaMiddleware.run(); }
Here's the problem in plain terms:
- When you use
import * as sagas, you're creating an object that holds all exports fromsagas.mock.js. Since you usedexport defaultfor your saga, this object has one key:"default", and its value is yourtaskCreationSagaGenerator function. - The
sagaMiddleware.run()method needs a Generator function as its first argument to start the saga. When you calledrun()with no arguments, you passed itundefined—which isn't a Generator function. That's exactly why you saw the error:saga argument must be a Generator function!.
3. Why Your Fix Solved It
When you updated the loop to:
for (let saga in sagas) { sagaMiddleware.run(sagas[saga]); }
sagas[saga]grabs the value from thesagasobject using the current key (which is"default"in your case). That value is your validtaskCreationSagaGenerator function—exactly whatrun()needs to start the saga.- Now the middleware knows which saga to execute, so it can start listening for the
REQUEST_TASK_CREATIONaction like you intended.
Quick Side Note
If you ever switch to using named exports instead of default (e.g., export function* taskCreationSaga()), the sagas object will have a key matching the function name (taskCreationSaga). Your loop will still work perfectly because sagas[saga] will still pull the correct Generator function.
内容的提问来源于stack exchange,提问作者humans

