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

Discord.js中出现Cannot read properties of undefined (reading 'set')错误求助

Discord.js 命令加载报错:TypeError: Cannot read properties of undefined (reading 'set') 解决方法

这个错误的核心原因是**client.commands未被初始化**——Discord.js的客户端实例默认不存在commands属性,你需要手动创建一个Collection(Discord.js内置的键值对集合类)来存储命令。

解决步骤:

  1. 导入Collection类
    确保你从discord.js中导入Collection:

    const { Client, Collection } = require('discord.js');
    
  2. 初始化client.commands集合
    在创建客户端实例后,立即为其添加commands属性并赋值为新的Collection:

    const client = new Client({ intents: [/* 填入你的必要网关意图,例如GatewayIntentBits.Guilds */] });
    client.commands = new Collection(); // 关键:初始化命令存储集合
    
  3. 验证命令文件结构
    确保每个./commands目录下的命令文件都正确导出了name属性,示例命令文件结构:

    module.exports = {
        name: 'ping',
        execute(interaction) {
            interaction.reply('Pong!');
        }
    };
    

修改后的完整代码示例:

const { Client, Collection } = require('discord.js');
const fs = require('fs');

// 初始化客户端(注意填写必要的网关意图)
const client = new Client({ intents: [/* 你的网关意图 */] });

// 初始化命令集合
client.commands = new Collection();

// 加载命令文件
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    // 额外添加校验,避免因命令文件缺失name属性导致的后续问题
    if ('name' in command) {
        client.commands.set(command.name, command);
    } else {
        console.warn(`[警告] 命令文件 ${file} 未定义name属性,已跳过加载`);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 14:39:53