Botkit controller.trigger()触发后Node.js应用崩溃问题排查
Botkit Slack机器人触发自定义事件后崩溃问题排查
我使用Botkit开发Slack机器人,编写了如下代码:
controller.hears('hi', 'direct_message', async(bot, message) => { controller.trigger('test', bot, message); }); controller.on('test', async (bot,message) => { await bot.reply(message, 'triggerd test'); });
上述代码执行后,Slack收到回复triggered test,但紧接着Node.js应用崩溃,抛出错误:
C:\Users\Lenovo\Documents\Nodejs Project\chatbots\slackbot\node_modules\botbuilder-core\lib\turnContext.js:387 this.responded = true; ^ TypeError: Cannot perform 'set' on a proxy that has been revoked at Proxy.<anonymous> (C:\Users\Lenovo\Documents\Nodejs Project\chatbots\slackbot\node_modules\botbuilder-core\lib\turnContext.js:387:36) at Generator.next (<anonymous>) at fulfilled (C:\Users\Lenovo\Documents\Nodejs Project\chatbots\slackbot\node_modules\botbuilder-core\lib\turnContext.js:9:58) at processTicksAndRejections (node:internal/process/task_queues:96:5)
而使用以下代码时应用不会崩溃:
controller.hears('hi', 'direct_message', async(bot, message) => { await bot.reply(message, 'triggerd test'); });
请问我的代码中遗漏了什么?
问题原因
触发自定义事件时直接传递原始bot实例,而Botkit的bot对象在当前对话回合结束后会被内部回收(对应的Proxy被撤销)。当test事件的异步回调中操作这个已被回收的bot实例时,就会触发该错误。
解决方法
触发事件时需要传递bot的上下文副本,而非原始实例。可以通过bot.createContext(message)创建新上下文,再将其传入触发事件:
controller.hears('hi', 'direct_message', async(bot, message) => { // 创建新的有效上下文 const context = await bot.createContext(message); // 用新上下文触发事件 controller.trigger('test', context, message); }); controller.on('test', async (bot, message) => { await bot.reply(message, 'triggered test'); });
这样就能保证事件回调中操作的是未被回收的Bot上下文,避免Proxy撤销导致的崩溃。
内容的提问来源于stack exchange,提问作者samsonmarandi
相关产品推荐
相关产品推荐

