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
相关产品推荐
相关产品推荐

