使用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.
相关产品推荐
相关产品推荐

