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

已声明async函数仍报await is only valid in async functions错误如何解决

问题根因

await关键字只能在标记为async的函数作用域内使用,你虽然给最外层的muteCheckTimer加了async标识,但你实际用到await的位置是在两层嵌套的回调函数内部:setInterval的匿名回调、db.each的结果回调,这两个回调都没有被标记为async,因此触发语法报错。

修复方法

给两层嵌套的回调都加上async前缀即可解决报错,修改后的代码如下:

const muteCheckTimer = async (client) => {
  setInterval(async () => {
    db.each(query, [], async (err, row) => {
        if(err) {
            console.log(err);
            return;
        }
        if(row) {
            let currentTimestamp = Date.now();
            if(currentTimestamp > row.mutedTimestamp) {
                let user = await client.users.fetch(row.userID);
                if(!user.member) { console.log('Not a user') }

                let MutedRole = user.member.guild.roles.cache.find((r) => r.name === "Muted");
                if(!MutedRole) { console.log("Muted role doesn't exists") }
                
                //await user.member.roles.remove(MutedRole);
                
            } else {
                console.log('MUTED');
            }
        }
    });
  }, 10000);
}
额外注意

建议在await相关逻辑外层包裹try...catch捕获异步操作可能抛出的异常,避免进程意外崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 10:33:00