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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 13:52:08