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

Discord.js v13调用setChannel报Cannot read properties of undefined错误求助

问题根因

你遇到的Cannot read properties of undefined (reading 'setChannel')报错,核心原因是newState.guild.members.fetch(user)是异步API,你没有添加await关键字,导致member变量实际存储的是Promise对象而非GuildMember实例,Promise不存在voice属性,因此调用member.voice.setChannel时触发了undefined属性读取错误。

修复方案

有两个可选修复方向,推荐使用第二种更简洁的写法:

  • 方案1:给成员fetch操作添加await,确保拿到正确的成员实例
  • 方案2:直接复用newState自带的member属性,不需要额外调用fetch请求用户和成员数据,减少不必要的API调用
修正后代码
const {Collection} = require('discord.js')
let privateVoice = new Collection()
const config = require('../config.json'); // 补全const避免全局变量污染

module.exports = async (bot, oldState, newState)=>{
  // 直接复用newState自带的成员数据,无需额外发起fetch请求
  const member = newState.member;
  const user = member.user;
  if(!oldState.channel && newState.channel.id === config.createChannel){
    const channel = await newState.guild.channels.create(user.tag,{
      type: "GUILD_VOICE",
      parent: newState.channel.parent
    });
    await member.voice.setChannel(channel); // 添加await方便捕获移动异常
    privateVoice.set(user.id, channel.id);
  }
};
额外注意事项
  • 确保机器人拥有移动成员、管理频道的服务器权限,否则创建频道或移动成员时仍然会抛出权限类错误
  • 给setChannel也加上await关键字,可以方便捕获移动失败的异常,降低后续排查问题的成本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:15:04