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

Discord.js出现Cannot read properties of undefined (reading 'members')报错求解决

问题解决与替代实现方案

报错原因

报错Cannot read properties of undefined (reading 'members')是因为代码里的guild变量未定义——你直接使用了guild,但没有从消息对象中获取当前服务器的实例。

基础修复方案

将guild替换为message.guild,同时处理args参数格式、私聊场景等边界情况:

if (command === "give") {
    message.channel.send('test');
    // 先判断命令是否在服务器内发送
    if (!message.guild) {
        return message.channel.send('这个命令只能在服务器内使用');
    }
    // 假设args是参数数组,取第一个元素作为目标用户ID
    const targetId = args[0];
    if (!targetId) {
        return message.channel.send('请提供要查询的用户ID');
    }
    // 从服务器成员缓存中查找目标用户
    const member = message.guild.members.cache.find(m => m.id === targetId);
    if (member) {
        message.channel.send('FOUND');
    } else {
        message.channel.send('who is that');
    }
}

更可靠的实现方案

成员缓存可能存在未加载全的情况,使用fetch方法直接从Discord API获取成员,避免缓存缺失问题:

if (command === "give") {
    message.channel.send('test');
    if (!message.guild) {
        return message.channel.send('这个命令只能在服务器内使用');
    }
    const targetId = args[0];
    if (!targetId) {
        return message.channel.send('请提供要查询的用户ID');
    }
    try {
        // 直接从API拉取成员信息,不受缓存限制
        const member = await message.guild.members.fetch(targetId);
        message.channel.send('FOUND');
    } catch (error) {
        // 捕获API请求错误,说明该ID不属于服务器成员
        message.channel.send('who is that');
    }
}

额外注意事项

  • 确保机器人拥有GUILD_MEMBERS权限,否则无法获取成员信息。
  • 若使用Discord.js v14及以上版本,客户端初始化时必须启用GuildMembers意图:
    const { Client, GatewayIntentBits } = require('discord.js');
    const client = new Client({
        intents: [
            GatewayIntentBits.Guilds,
            GatewayIntentBits.GuildMembers,
            GatewayIntentBits.MessageContent
        ]
    });
    

内容的提问来源于stack exchange,提问作者희민TV - HeeminTV

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 22:52:09