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

使用Discord.js编写事件处理器时遇fetch读取未定义属性的TypeError错误

Discord.js TypeError: Cannot read properties of undefined (reading 'fetch') 问题解决

错误原因

这个错误核心是applicationCommands变量变为undefined,导致调用fetch()方法时触发报错,具体问题出在两处:

  • 客户端未就绪时,client.application还未初始化,直接访问client.application.commands会得到undefined
  • else分支错误地给client.application.commands加了await,它本身是同步获取的管理器对象,不需要异步等待

修复方案

不需要额外执行npm install操作,只需修正代码逻辑并确保客户端状态正确:

1. 确保客户端已就绪

调用该函数前,必须保证Discord客户端已经触发ready事件,否则client.application可能还未完成初始化。

2. 修正代码

module.exports = async (client, guildId) => {
  let applicationCommands;

  if (guildId) {
    const guild = await client.guilds.fetch(guildId);
    if (!guild) throw new Error('无法获取指定服务器');
    applicationCommands = guild.commands;
  } else {
    if (!client.application) throw new Error('客户端应用未初始化,请确保client已完成就绪');
    // 移除多余的await,直接赋值命令管理器
    applicationCommands = client.application.commands;
  }

  await applicationCommands.fetch();
  return applicationCommands;
};

3. 版本检查

确认你安装的Discord.js版本为v14及以上,该代码基于v14的API编写。可以通过以下命令查看版本:

npm list discord.js

补充说明

  • guild.commands和client.application.commands都是ApplicationCommandManager实例,属于同步获取的对象,只有调用其fetch()方法时才需要异步等待。
  • 增加空值检查可以提前抛出明确错误,便于快速排查问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 10:00:07