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

Vue+Vuex项目中async/await的Await未等待问题求助

问题分析与解决

核心问题

你混淆了Vuex getter和action的作用:

  • getter是同步获取state现有值的方法,不支持异步操作,await getter完全无效,它会立即返回当前state里的内容(也就是你看到的Observer,属于Vue的响应式包装对象)。
  • getInternalNotifications是Vuex action(从参数{ dispatch }可判断),它才是处理异步逻辑的地方,但你在组件里根本没调用这个action,反而去await getter,导致代码没等待异步操作完成就继续执行了。

修复步骤

1. 组件中调用action并await其结果

把组件里的getNotifications函数改成调用action,而非await getter:

async getNotifications() {
    console.log('1')

    // 调用action并等待异步逻辑执行完成
    await this.$store.dispatch('AppData/getInternalNotifications', {
        cid: 你的cid值,
        user: 你的user对象,
        roles: 你的roles数组,
        isSupperAdmin: 你的权限标识
    })

    console.log('2')

    // 异步操作完成后,再从getter获取最终结果
    const internalNotifications = this.$store.getters['AppData/getInternalNotifications']

    if(internalNotifications) {
        this.notifications = internalNotifications
        this.message = true
        console.log('4 ', internalNotifications)
    }
}

2. 确保action正确更新state

你的action已经是async函数(自动返回Promise),但需要确保addInternalNotification mutation把处理后的internalNotifications正确存入state,这样getter才能拿到最新值:

// 示例mutation
mutations: {
    addInternalNotification(state, payload) {
        state.internalNotifications = payload
    }
}

// 对应getter
getters: {
    getInternalNotifications: state => state.internalNotifications
}

3. 日志顺序修正

修复后,控制台日志顺序会符合预期:1 → getInternalNotifications → 3 → 2 → 4,因为组件会等待action内所有异步操作完成后,才会执行后续代码。

额外优化建议

避免在action的循环里逐个await数据库请求,改用Promise.all批量处理以提升性能:

// 替换原有的for循环
const notificationPromises = getAllNotifications.docs.map(async notificationDoc => {
    let notification = notificationDoc.data()
    notification.id = notificationDoc.id

    const getAllReadNotifications = await db
        .collection('notificationsread')
        .where('notificationid', '==', notification.id)
        .where('userid', '==', user.uid)
        .get()

    return getAllReadNotifications.empty ? notification : null
})

// 批量等待所有请求完成,过滤掉已读的通知
internalNotifications = (await Promise.all(notificationPromises)).filter(Boolean)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:10:51