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

Discord.js v14.9.0音乐机器人报错:Cannot read properties of undefined (reading 'name')

解决Discord.js 14.9.0中Cannot read properties of undefined (reading 'name')报错

这个报错的核心原因是你加载的某个命令文件中,导出的对象没有data属性,导致command.data为undefined,无法读取name字段。下面是具体排查和解决方法:

  • 检查命令文件的导出结构
    Discord.js v14的斜杠命令必须导出包含data属性的对象,data是SlashCommandBuilder的实例。确保每个commands文件夹下的.js文件都遵循这个结构:

    const { SlashCommandBuilder } = require('discord.js');
    
    module.exports = {
        data: new SlashCommandBuilder()
            .setName('你的命令名')
            .setDescription('命令描述'),
        async execute(interaction) {
            // 命令执行逻辑
        }
    };
    

    如果某个文件没有导出data,或者data未正确初始化,就会触发该错误。

  • 排查具体出错的命令文件
    在循环中添加错误捕获和检查逻辑,快速定位问题文件:

    for (const file of commandFiles) {
        const filePath = path.join(commandsPath, file);
        try {
            const command = require(filePath);
            // 检查是否存在合法的data属性
            if (!command?.data) {
                console.warn(`[警告] 命令文件 ${file} 未正确导出data对象,已跳过`);
                continue;
            }
            client.commands.set(command.data.name, command);
            commands.push(command.data.toJSON());
        } catch (err) {
            console.error(`[错误] 加载命令文件 ${file} 失败:`, err);
        }
    }
    

    运行后控制台会直接提示问题文件,针对性修复即可。

  • 确认命令目录路径正确
    确保commandsPath指向的是存放命令文件的真实目录,比如入口文件在src文件夹、命令在src/commands时,path.join(__dirname, "commands")是正确的;如果目录名拼写错误(比如写成command或Commands),会导致加载错误的文件。

内容的提问来源于stack exchange,提问作者Shan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:37:11