TypeError: Cannot read property 'displayAvatarURL' of undefined: Get this error when trying to ping another person to get their avatar

TypeError: Cannot read property 'displayAvatarURL' of undefined: Get this error when trying to ping another person to get their avatar

    } else if (command === 'avatar') {
        const target = message.mentions.users.first();
       
        if (target) {
            const userTarget = message.guild.members.cache.get(target.id);
            message.channel.send(message.userTarget.displayAvatarURL());
        } else if (!target) {
            message.channel.send(message.author.displayAvatarURL());
        } 
     }
 });    

else if 语句工作正常,但是当有人要获取那个人的头像时,它就不起作用了。

Message has no userTarget property. If you want to get the avatar url of the target member, then access the user property of the returned member and call the display method 那里:

userTarget.user.displayAvatarURL()

或者,您的 target 变量已经存储了目标用户,因此您不需要获取他们的成员对象并将其存储在 userTarget 中。您可以直接致电:

target.displayAvatarURL()