You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用discord.js开发Discord机器人出现TypeError: this.test is not a function如何解决

问题根源

你遇到的报错是this上下文指向错误导致的:当你直接把类的普通方法this.onReady作为事件回调传入client.once时,方法执行时的this会被绑定到触发事件的Client实例上,而非你自己定义的DiscordBot类实例,此时的this上不存在test方法,就会抛出类型错误。

解决方案

你可以任选以下任意一种方式修复:

  • 方案1:用箭头函数包裹回调,继承构造函数内的this指向(最常用)
    修改构造函数内的事件绑定代码即可:
    this.bot.once('ready', (client) => this.onReady(client));
    
  • 方案2:用bind显式绑定方法的this指向
    this.bot.once('ready', this.onReady.bind(this));
    
  • 方案3:将onReady定义为类的箭头函数字段,永久绑定类实例的this
    修改方法定义即可:
    class DiscordBot {
      constructor() {
          this.bot = new Client({ intents: [...] });
          this.bot.once('ready', this.onReady);
      }
    
      // 定义为箭头函数类字段
      onReady = async (client) => {
          console.log('Ready!');
          this.bot = client;
          this.text_channel = await this.bot.channels.fetch(id)
          this.test();
      }
    
      test() {
          // stuff
      }
    }
    

内容的提问来源于stack exchange,提问作者davide m.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 06:15:02