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

Vue项目中后端持续轮询请求卡顿问题求助

问题分析与解决方案

你的问题核心在于setInterval的固定间隔轮询会导致请求叠加:不管前一次lookup请求是否完成,到15秒就会发起新请求,当首次请求本身耗时较长(比如超过15秒),就会同时存在多个pending的请求,触发浏览器同域名并发请求限制(通常最多6个),或者后端处理队列积压,最终表现为请求卡顿20秒。

解决方法:改为「请求完成后再轮询」

把固定间隔的setInterval换成基于请求完成的setTimeout,确保同一时间只有一个请求在处理,避免叠加:

修改后的代码

data() {
  return {
    responseStatus: null, // 条件渲染用状态变量
    response: null,
    pollTimeoutId: null // 用于控制轮询的定时器ID
  }
},

created() {
  this.lookup() // 发起首次请求
},

methods: {
  lookup() {
    // 可选:给请求加上超时时间,避免单个请求卡住太久
    axios.get(`...`, { timeout: 10000 })
      .then((res) => {
        this.response = res.data
        console.log(this.response, 'response')
        
        if (this.response.active) {
          this.responseStatus = 0
          // 本次请求完成后,等待15秒再发起下一次轮询
          this.pollTimeoutId = setTimeout(() => {
            this.lookup()
          }, 15000)
        } else {
          this.responseStatus = 1
          this.clearPoll() // 任务完成,停止轮询
        }
      })
      .catch((e) => {
        console.log(e)
        this.responseStatus = 2
        this.clearPoll() // 请求失败,停止轮询
      })
  },
  clearPoll() {
    if (this.pollTimeoutId) {
      clearTimeout(this.pollTimeoutId)
      this.pollTimeoutId = null
    }
  }
},

beforeUnmount() {
  this.clearPoll() // 组件销毁时清理定时器,防止内存泄漏
}

关键改进点

  1. 避免请求叠加:只有当前请求成功/失败后,才会在15秒后发起下一次请求,确保同一时间最多一个请求在处理,彻底解决卡顿问题。
  2. 内存泄漏防护:新增beforeUnmount钩子清理定时器,避免组件销毁后定时器仍在运行。
  3. 可选优化:给axios请求添加超时配置,防止单个请求因后端异常卡住太久。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 00:47:02