Vue3中Lodash debounce使用异常求助:Pinia代码排查
问题排查与修复
你这段代码的核心问题有两个:
- 防抖函数未执行:Lodash的
debounce返回的是一个待执行的防抖函数,你只创建了它但没调用,所以this.loading = false永远不会触发。 - 每次请求都会生成新的防抖实例:如果直接在
then回调里创建防抖函数,每次调用fetchUsers都会生成一个全新的防抖函数,无法实现真正的防抖效果。
修复方案一:仅延迟关闭loading
如果只是想延迟1秒关闭loading,不需要对请求本身防抖,只需补全函数调用:
actions: { fetchUsers(targetAppId?: string) { this.loading = true; AppsService.getUsers(targetAppId) .then(response => { this.users = response.data.users // 调用debounce返回的函数 debounce(() => { this.loading = false }, 1000)() }) // 必须处理错误,避免loading一直处于true .catch(() => { this.loading = false }) }, }
修复方案二:对请求函数整体防抖(避免重复触发)
如果要防止短时间内重复调用fetchUsers接口,应该把防抖逻辑抽出来绑定到action上:
import { debounce } from 'lodash' actions: { // 用普通函数保证this指向Pinia store实例 fetchUsers: debounce(function(targetAppId?: string) { this.loading = true; AppsService.getUsers(targetAppId) .then(response => { this.users = response.data.users this.loading = false }) .catch(() => { this.loading = false }) }, 1000), }
内容的提问来源于stack exchange,提问作者Gonzalo Diaz Ailan
相关产品推荐
相关产品推荐

