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

Discord.js报错:TypeError: 无法读取undefined的'username'属性

问题:Discord.js中client.users.cache.get()返回undefined导致报错

我定义的victim是输入的服务器有效用户ID字符串,但调用client.users.cache.get(victim).username时触发错误:Cannot read properties of undefined (reading 'username')。此前在其他代码块用过该语句,本次是首次在当前代码中使用,相关代码如下:

const victim = interaction.options.get("user").value
const reason = interaction.options.get("reason").value
const time = Date.now()
                
client.guilds.cache.get("808701451399725116").channels.cache.get("858644165038047262").send({ 
                    embeds: [
                        new EmbedBuilder()
                            .setTitle("New Blacklist")
                            .setFields(
                                {
                                    name:"User",
                                    value:`Name: **${client.users.cache.get(victim).username}*** \n`+ `Discrim: **${client.users.cache.get(victim).discriminator}** \n` + `User Id: **${victim}**`,
                                    inline: true
                                },
                                {
                                    name:"Reason",
                                    value:`${reason}`,
                                    inline: true
                                },
                                {
                                    name: "Time (epoch)",
                                    value: `${time}`
                                }
                            )
                            .setThumbnail(client.users.cache.get(victim).avatarURL())
                            .setImage("https://cdn.discordapp.com/emojis/860970578684018700.webp?size=160&quality=lossless")
                    ]
                });

原因及解决方案

核心原因

Discord.js的用户缓存(client.users.cache)仅存储机器人已经交互过或共同在服务器内见过的用户,哪怕是当前服务器的有效用户,如果机器人没有缓存该用户数据,cache.get()就会返回undefined,进而导致读取username属性时报错。

解决步骤

  1. 改用fetch()主动获取用户
    不要依赖本地缓存,直接调用client.users.fetch(victim)从Discord API拉取用户信息,无论缓存中是否存在该用户都能获取到数据。

  2. 优化代码避免重复调用
    多次重复调用client.users.cache.get(victim)不仅冗余,还会放大报错风险,建议先获取用户对象再复用。

  3. 添加错误处理
    捕获fetch()可能出现的异常(比如ID无效、API请求失败),避免机器人崩溃并给用户反馈。


修改后的代码示例

const victim = interaction.options.get("user").value;
const reason = interaction.options.get("reason").value;
const time = Date.now();

// 提前获取目标频道,减少重复缓存查询
const targetChannel = client.guilds.cache.get("808701451399725116").channels.cache.get("858644165038047262");

// 主动拉取用户数据,处理异步逻辑
client.users.fetch(victim)
  .then(user => {
    targetChannel.send({ 
      embeds: [
        new EmbedBuilder()
          .setTitle("New Blacklist")
          .setFields(
            {
              name:"User",
              value:`Name: **${user.username}** \nDiscrim: **${user.discriminator}** \nUser Id: **${victim}**`,
              inline: true
            },
            {
              name:"Reason",
              value:`${reason}`,
              inline: true
            },
            {
              name: "Time (epoch)",
              value: `${time}`
            }
          )
          .setThumbnail(user.avatarURL())
          .setImage("https://cdn.discordapp.com/emojis/860970578684018700.webp?size=160&quality=lossless")
      ]
    });
  })
  .catch(err => {
    console.error("获取用户失败:", err);
    interaction.reply({ content: "无法获取目标用户信息,请检查用户ID是否正确。", ephemeral: true });
  });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 16:17:44