" TypeError: Cannot read property 'cache' of undefined" and "TypeError: Cannot read property 'roles' of null"

" TypeError: Cannot read property 'cache' of undefined" and "TypeError: Cannot read property 'roles' of null"

该机器人之前工作得很好,但突然崩溃并出现错误“TypeError:无法读取未定义的 属性 'cache'”,即使它没有,我也无法使用机器人添加角色。(TypeError: Cannot read 属性 'roles' of null) discord 改变了什么吗?请帮我解决一下这个。谢谢。

这是我得到的错误:https://pastebin.com/PWc8MAvU

下面是我一直在使用的代码

const Discord = require('discord.js');
const bot = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION','GUILD_MEMBER', 'USER'] });

bot.on('messageReactionAdd', async (reaction, user) => {
    if (reaction.partial) {
        try {
            await reaction.fetch();
        } catch (error) {
            console.log('Error when fetch msg ', error);
            return;
        }
    }
    
    if(reaction.message.id === "the id of message for users to react to"){
        if(reaction.emoji.name === ''){
            console.log(user.username+' verified')            
            let member = bot.guilds.resolve('My server's id').members.resolve(user.id);
            member.roles.add('Id of the role I want to add');
        }
    }
});

您的问题是,有时,当您尝试获取他们的角色时,成员尚未缓存(默认情况下,只有一小部分成员被缓存)。而不是使用 resolve(), I would suggest using fetch() 和异步系统,所以如果用户没有被缓存,机器人将在获取他们的角色之前先缓存它。

const Discord = require('discord.js');
const bot = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION','GUILD_MEMBER', 'USER'] });

bot.on('messageReactionAdd', async (reaction, user) => {
    if (reaction.partial) {
        try {
            await reaction.fetch();
        } catch (error) {
            console.log('Error when fetch msg ', error);
            return;
        }
    }
    
    if(reaction.message.id === "the id of message for users to react to"){
        if(reaction.emoji.name === ''){
            console.log(user.username+' verified');
            let guild = bot.guilds.cache.get("My server's id");
            guild.members.fetch(user.id)
            .then(member -> {
                member.roles.add('Id of the role I want to add');
            }).catch(console.error);
        }
    }
});