JS推送Discord webhook时触发userId is not defined报错
问题现象
- 调用Roblox接口可正常获取对应用户名,代码能正常输出用户名内容
- 构造Discord webhook推送消息的缩略图字段、拼接userId参数时,运行抛出
userId is not defined错误 - 移除缩略图配置项时代码可正常运行,需求为同时保留userId、username的正常调用,实现Roblox交易通知推送功能
原实现代码如下:
const getUsername = userId => new Promise(resolve => { fetch('https://users.roblox.com/v1/users/' + userId) .then(res => res.json()) .then(body => resolve(body.name || 'Unknown')) .catch(() => resolve('Unknown')) }) (async () => { const username = await getUsername(nextInQueue.offers[0].userId); consola.success(`[${username}] has ok items`) fetch(config.webhook, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ "content": null, "embeds": [ { "title": ":tada: Trade sent to: " + username + " :tada:", "color": 28420, "fields": [ { "name": "Cool Items:", "value": itemNameList.join('\n') }, { "name": "Okay items:", "value": toreceiveList.join('\n') } ], "author": { "name": "Expoorttoo", "icon_url": "https://i.pinimg.com/736x/4b/69/74/4b6974aef5d96580140ef2686072af3f.jpg" }, "footer": { "text": Sentto.toLocaleString() + " sent & " + tradeQueue.length.toLocaleString() + " set in queue" }, "thumbnail": { "url": "https://www.roblox.com/headshot-thumbnail/image?userId=" + userId + "&width=420&height=420&format=png" } } ] }) }) })().catch(); }
错误原因
userId是getUsername函数的形参,作用域仅限getUsername函数内部。外层异步立即执行函数拼接缩略图URL时直接引用userId,当前作用域下没有声明该变量,直接触发未定义报错。
修复方案
在异步函数作用域内先声明变量存储目标userId,再分别用于调用接口获取用户名、拼接缩略图URL即可。
修复后可运行代码:
const getUsername = userId => new Promise(resolve => { fetch('https://users.roblox.com/v1/users/' + userId) .then(res => res.json()) .then(body => resolve(body.name || 'Unknown')) .catch(() => resolve('Unknown')) }) (async () => { // 提前将userId存入当前作用域变量 const targetUserId = nextInQueue.offers[0].userId; const username = await getUsername(targetUserId); consola.success(`[${username}] has ok items`) fetch(config.webhook, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ "content": null, "embeds": [ { "title": ":tada: Trade sent to: " + username + " :tada:", "color": 28420, "fields": [ { "name": "Cool Items:", "value": itemNameList.join('\n') }, { "name": "Okay items:", "value": toreceiveList.join('\n') } ], "author": { "name": "Expoorttoo", "icon_url": "https://i.pinimg.com/736x/4b/69/74/4b6974aef5d96580140ef2686072af3f.jpg" }, "footer": { "text": Sentto.toLocaleString() + " sent & " + tradeQueue.length.toLocaleString() + " set in queue" }, "thumbnail": { // 调用当前作用域存储的userId变量拼接地址 "url": `https://www.roblox.com/headshot-thumbnail/image?userId=${targetUserId}&width=420&height=420&format=png` } } ] }) }) // 补全catch错误回调,方便后续排查运行问题 })().catch(console.error);
内容的提问来源于stack exchange,提问作者user18383426
相关产品推荐
相关产品推荐

