使用@pinia/nuxt时setInterval循环重复触发外部HTTP请求问题
问题解决:计时器启动时仅发起一次HTTP请求
问题根源
你的代码中,syncTimer 方法直接使用响应式的 this.timer 作为请求体,而 Nuxt 的 useFetch(通过 backendAPI 调用)会自动追踪响应式依赖的变化。当 setInterval 每秒修改 this.timer.time 时,useFetch 会判定请求参数发生变化,从而重复发起 POST 请求。
解决方案
1. 使用计时器状态快照作为请求体
在 syncTimer 中生成当前 timer 的普通对象快照,切断响应式关联,避免后续状态变化触发重复请求:
syncTimer() { // 生成当前timer的快照,脱离响应式追踪 const timerSnapshot = { ...this.timer }; backendAPI<Timer>('/api/timer', { method: 'POST', body: timerSnapshot }).then(({ error, data }) => { if (!error.value) { const id = data.value?.id ?? "" this.timer.id = id this.timer.state = "created" } }) }
2. 防止重复调用启动方法
在 start 方法开头增加判断,避免用户多次触发启动操作导致重复执行 syncTimer:
start() { // 如果计时器已在运行,直接返回 if (this.timer.isRunning) return; this.timer.isRunning = true this.syncTimer() if (!this.timer.timer) { this.timer.timer = setInterval(() => { if (this.timer.time > 0) { this.timer.time-- } else { clearInterval(this.timer.timer) this.reset() } }, 1000) } }
说明
- 快照方式确保请求体仅使用启动瞬间的计时器状态,后续的倒计时数值变化不会触发新的请求。
- 重复调用判断避免了多次点击启动按钮导致的多请求和多定时器冲突问题。
内容的提问来源于stack exchange,提问作者titoti
相关产品推荐
相关产品推荐

