Discord urban-dictionary斜杠命令读取list属性TypeError报错问题问询
错误根源
报错的核心原因是axios.get()为异步请求方法,默认返回Promise对象,你没有使用await关键字等待请求完成就直接进行解构赋值,Promise对象本身不存在data属性,因此data为undefined,读取undefined.list就触发了该报错。
同时你的代码还存在多个潜在问题会导致后续运行报错:
- 空的
catch回调会吞掉所有请求错误,请求失败时返回值为undefined,即使加了await后续解构逻辑依然会报错 - 没有判断接口返回的
list是否为空数组,如果搜索关键词无匹配结果,解构出的answer为undefined,后续读取answer.word等属性会继续报错 - 承载这段代码的处理函数需要用
async修饰为异步函数,否则无法使用await关键字
修正后的参考代码
// 首先确保你的处理函数是异步的,示例:client.on('interactionCreate', async interaction => { let query = interaction.options.getString('search') query = encodeURIComponent(query); try { // 加await等待请求返回结果 const { data: { list } } = await axios.get(`https://api.urbandictionary.com/v0/define?term=${query}`) // 对搜索结果判空 if (!list || list.length === 0) { return interaction.reply({ content: '未找到对应词条的搜索结果', ephemeral: true }) } const [answer] = list; const embed = new MessageEmbed() .setTitle(answer.word) .setURL(answer.permalink) .setColor("#380002") .setDescription(trim(answer.definition)) .addField("Example", trim(answer.example), false) .addField("Upvotes", `** ** ${answer.thumbs_up}`, true) .addField("Downvotes", `** ** ${answer.thumbs_down}`, true) .setFooter(`Author: ${answer.author}`); await interaction.reply({embeds: [embed], ephemeral: false}) } catch (err) { // 统一处理异常 console.error('搜索请求出错:', err) interaction.reply({ content: '搜索词条时出现异常,请稍后重试', ephemeral: true }).catch(() => {}) }
内容的提问来源于stack exchange,提问作者MegaMix_Craft
相关产品推荐
相关产品推荐

