本文介绍了无法导出生成器功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试导出生成器函数以便在Redux-Saga中使用时,ES-Lint告诉我代码中有错误:

When attempting to export a generator function in order to use in a Redux-Saga, ES-Lint is telling me that I have an error in my code:

[eslint] Expected a function declaration. (func-style)

它以目前的状态导出,并且该规则当前被忽略:

It exports just fine the way that it is currently, and the rule is currently being ignored:

/*eslint-disable func-style*/
const myExampleSaga = function* () {
        yield takeEvery('DO_SOMETHING_REQUEST', andDoThisFunc);
};
export default myExampleSaga;

对于ES-Lint不支持生成器(或至少看起来是这样)的事实,我大致上可以接受,但是我想知道为什么以下代码不起作用 >:

I am more or less okay with the fact that ES-Lint does not support generators (or at least it would seem that way), however I would like to know why the following code does not work:

export default function* () {
    yield takeEvery('DO_SOMETHING_REQUEST', andDoThisFunc);
}

显示以下错误消息:

undefined is not an object (evaluating 'regeneratorRuntime.mark')

我的rootSaga抛出了错误消息,看起来像这样:

The error message is being thrown from my rootSaga, which looks like this:

/*eslint-disable func-style*/
export const rootSaga = function* rootSaga() {
    yield all([
        spawn(myExampleSaga)
    ]);
};

有人可以告诉我为什么上面的代码无效吗?我认为这与起吊有关,但是我无法找到任何无效的原因.

Can anyone tell me why the above code is invalid? I think it has something to do with hoisting, however I was not able to find any reason why that would be invalid.

推荐答案

这是regenerator-transform babel插件的著名问题.通常用于使用sagas进行代码转译.这个问题也会影响async函数,因为它们也是由regenerator-transform机制实现的.

This is well-known issue of regenerator-transform babel plugin, which is commonly used for transpiling code with sagas. That issue also affects async functions, because they are implemented by regenerator-transform mechanism too.

export default function* () {
    yield takeEvery('DO_SOMETHING_REQUEST', andDoThisFunc);
}

,可能有两个问题.首先是省略包含regenerator-runtime的依赖关系,这是强制性的.其次是函数提升,因此如果发生顺序很重要,则应隐式指定它.

After transforming that code , there can be two issues. First is omitting inclusion of regenerator-runtime dependency, which is mandatory. Second is function hoisting, so if occurrence order matters, it should be specified implicitly.

正确的解决方法是:

import 'regenerator-runtime';
const mySaga = function* () {
    yield takeEvery('DO_SOMETHING_REQUEST', andDoThisFunc);
}
export default mySaga;

这篇关于无法导出生成器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 11:00
查看更多