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

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属性也是不能访问

阅读 7.2k
3 个回答

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

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

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

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

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

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

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

缺了this

用this.ctx

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

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

推荐问题