eggjs 在定时器访问service提示Cannot read property 'service' of undefined

发布于 2022-09-06 10:12:40 字数 901 浏览 21 评论 0

update_article.js(schedule目录下):

const Subscription = require('egg').Subscription;

class UpdateArticleStatus extends Subscription {
    // 通过 schedule 属性来设置定时任务的执行间隔等配置
    static get schedule() {
        return {
            interval: '2s', // 1 分钟间隔
            type: 'all', // 指定所有的 worker 都需要执行
        };
    }

    * subscribe(ctx) {
        const res = yield ctx.service.article.getAllArticles(1);
        console.log(res);
    }
}
module.exports = UpdateArticleStatus;

运行提示:
excute error. Cannot read property 'service' of undefined

我照官网的例子:

module.exports = {
  schedule: {
    interval: '1m', // 1 分钟间隔
    type: 'all', // 指定所有的 worker 都需要执行
  },
  * task(ctx) {
    const res = yield ctx.curl('http://www.api.com/cache', {
      dataType: 'json',
    });
    ctx.app.cache = res.data;
  },
};

发现curl属性也是不能访问

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

や莫失莫忘 2022-09-13 10:12:40

它已经提示你了, Cannot read property 'service' of undefined
说明 service 属性前面的 ctx 是 undefined。

你这属于混着写,不遵守他示例的格式。

第一个写法里面,subscribe 函数是没有 ctx 这个参数的。

第二个属于简写写法,ctx.curl 是可以访问的啊,你可以在 task 函数里直接

console.log(ctx.curl.toString());

是可以访问到函数原型的,没有明白你这个 curl 无法访问的意思。

追风人 2022-09-13 10:12:40

创建匿名ctx
const ctx = app.createAnonymousContext()

海未深 2022-09-13 10:12:40

缺了this

用this.ctx

而且要记得在头部引用 const Subscription = require('egg').Subscription;

另外egg2.0已经支持await如果升级到2.0,可以用await

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文