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

Discord.js调用user.roles.map报cannot read map of undefined错误如何解决

问题解决

报错根因

  • 你遇到的cannot read property 'map' of undefined报错核心原因是写法错误:Discord.js 提供的user是全局用户实例,仅存储跨服务器的通用用户信息(用户名、ID、头像等),没有roles属性,因此user.roles为undefined,调用map方法自然抛出对应错误。
  • 服务器角色数据仅存储在对应服务器的GuildMember实例中,你需要从服务器成员缓存中取出对应用户的成员实例,再读取角色列表。

代码优化点

你原代码中两个完全相同的message.id和emoji.name判断可以合并,无需分开写角色添加、移除逻辑,同时提前存储GuildMember实例避免重复从缓存取值。

修改后可运行代码

client.on('messageReactionAdd', async(reaction, user) => {
    if(reaction.message.partial) await reaction.message.fetch();
    if(reaction.partial) await reaction.fetch();
    if(user.bot) return;
    if(!reaction.message.guild) return;
    // 合并重复判断逻辑
    if(reaction.message.id === '881057147692138546' && reaction.emoji.name === 'r_check_pde') {
        // 提前取出当前用户在服务器的GuildMember实例
        const member = reaction.message.guild.members.cache.get(user.id);
        await member.roles.add('879244179945963571');
        await member.roles.remove('879957726128648263');
        // 从member实例读取角色列表,v12以上版本需访问roles.cache获取角色集合
        const roleList = member.roles.cache.map(r => `${r}`).join(' | ');
        // 增加异常捕获避免用户关闭私信权限导致机器人崩溃
        user.send(
            new Discord.MessageEmbed()
            .setDescription("Registrado")
            .addField('Roles:', roleList, true)
        ).catch(err => console.log('私信发送失败,用户可能关闭了陌生人私信权限:', err));
    }
})

额外说明

如果你使用的是Discord.js v14及以上版本,MessageEmbed需要从discord.js包中单独导入,角色操作相关逻辑和上述代码保持一致。


内容的提问来源于stack exchange,提问作者João Victor Sales

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:24:01