Discord.js报错:Cannot read properties of undefined (reading 'execute')修复求助
修复Discord.js前缀命令不存在时的TypeError错误
错误原因
当输入前缀但后续内容不是已定义的命令时,commands.get(args[0])会返回undefined,此时直接调用.execute()就会触发TypeError: Cannot read properties of undefined (reading 'execute'),导致程序崩溃。
修复方案
在调用命令的execute方法前,先检查获取到的命令是否存在。如果不存在,直接终止后续逻辑(可选给用户提示未知命令)。
修改后的Message事件代码
//Message Events client.on('messageCreate', message => { //PREFIX if (!message.content.startsWith(PREFIX) || message.author.bot) return; let args = message.content.substring(PREFIX.length).trim().split(" ") if (!args[0]) return; // 获取命令并检查是否存在 const command = commands.get(args[0]); if (!command) { // 可选:回复用户提示未知命令 // message.reply('未知命令,请输入正确指令!'); return; } // 执行命令 command.execute(message, args) })
额外检查
确保你的每个命令文件都正确导出了name和execute属性,示例命令文件结构:
module.exports = { name: 'ping', execute(message, args) { message.reply('pong'); } }
这样修改后,当用户输入不存在的前缀命令时,程序会直接返回,不会触发错误崩溃。
内容的提问来源于stack exchange,提问作者dav-devp
相关产品推荐
相关产品推荐

