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

如何修复Discordjs中TypeError: Cannot read properties of undefined (reading 'toLowerCase')错误

问题定位

报错指向你loader.js第26行的command.name.toLowerCase()代码,触发原因是你加载的某一个命令JS文件导出的内容中没有name属性,导致command.name为undefined,调用toLowerCase方法时抛出类型错误。

因为你此前运行正常,今日才触发报错,优先排查你今日新增/修改过的./commands/目录下的文件即可。如果找不到具体文件,可以临时修改loader代码快速定位:

const command = require(`../commands/${dirs}/${file}`);
// 新增下面这行代码,运行后会打印出有问题的文件路径
if (!command || !command.name) console.log(`无效命令文件:${dirs}/${file},导出内容:`, command);
console.log(`-> Loaded command ${command.name.toLowerCase()}`);

运行机器人后,终端输出的「无效命令文件」对应的就是出错的文件。

常见出错原因

  1. 命令文件漏写了导出对象的name字段
  2. 导出语法错误,比如把module.exports = {}写错,或者name拼写错误(比如写成Name/nama等)
  3. 命令文件存在语法错误,导致require导入后返回异常对象

修复方案

方案1:修复出错的命令文件

确保所有命令文件的导出结构符合要求,示例正确的命令文件写法:

module.exports = {
  name: 'example', // 必须存在该字段,不能遗漏
  description: '示例命令',
  execute(client, interaction) {
    // 命令执行逻辑
  }
}

方案2:给加载逻辑加兜底(推荐)

可以修改loader代码,避免单个命令出错导致整个机器人无法启动:

const command = require(`../commands/${dirs}/${file}`);
// 加校验,无效命令直接跳过
if (!command || !command.name) {
  console.log(`跳过无效命令:${dirs}/${file},缺少name属性`);
  continue;
}
const commandName = command.name.toLowerCase();
console.log(`-> Loaded command ${commandName}`);
client.commands.set(commandName, command);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:36:03