Discord.JS机器人报错:TypeError: 无法读取undefined的'name'属性
解决Discord.js中Cannot read properties of undefined (reading 'name')错误
错误原因
这条错误说明你循环加载命令文件时,某个command对象的data属性为undefined,导致无法读取name字段。
排查与修复步骤
检查所有命令文件的导出结构
确保commands文件夹下的每个.js命令文件都正确导出包含data属性的对象,示例结构如下:const { SlashCommandBuilder } = require('discord.js'); module.exports = { data: new SlashCommandBuilder() .setName('你的命令名') .setDescription('命令描述'), async execute(interaction) { // 命令执行逻辑 } };重点确认:没有遗漏
data属性,data是SlashCommandBuilder(或同类构造器)的实例,且正确调用了setName方法。移除重复的命令加载代码
你的代码中先手动加载了help命令:client.commands.set("help", require("./commands/help"));随后循环又会自动加载
help.js,这会导致重复注册,可能引发异常。删除这行手动加载的代码,统一由循环处理所有命令文件。过滤非命令文件
确认commands文件夹中没有无关的.js文件(比如工具类、配置文件),如果有,要么移到其他目录,要么修改过滤逻辑,只加载符合命令结构的文件。可以在循环里增加判断:for (const file of commandFiles) { const filePath = path.join(commandsPath, file); const command = require(filePath); // 增加判断,避免加载不符合结构的文件 if ('data' in command && 'execute' in command) { client.commands.set(command.data.name, command); commands.push(command.data.toJSON()); } else { console.log(`[警告] 命令文件${filePath}缺少必要的data或execute属性`); } }
内容的提问来源于stack exchange,提问作者clownidze
相关产品推荐
相关产品推荐

