Vuex dispatch触发无限循环?绑定:href的调用函数持续反复执行求助
无限循环问题根因
- Vue的动态属性绑定(比如
:href)中的表达式会在每次组件重新渲染时都重新执行,目的是实时计算最新的属性值。 - 你在
authenticationChoice方法里执行了两个会触发组件重新渲染的副作用操作:- 修改了Vuex的响应式状态
$store.state.gitSourceAuthenticationChoice - 异步请求完成后修改了组件自身的响应式属性
navigationURL
- 修改了Vuex的响应式状态
- 执行逻辑形成闭环:渲染组件 → 执行
authenticationChoice→ 修改响应式数据 → 触发组件重新渲染 → 再次执行authenticationChoice,最终形成无限循环。
额外补充:authenticationChoice是异步逻辑,首次调用时$store.dispatch还未返回,你直接return的navigationURL是初始值,等异步回调更新navigationURL后会再次触发渲染,进一步放大了循环问题。
修复方案
核心原则:不要在属性绑定表达式中执行带有副作用的方法,属性绑定仅用来读取最终值,副作用操作(修改状态、发请求)放到事件回调或生命周期钩子中执行。
方案1:点击时才生成跳转链接(推荐)
如果需求是用户点击链接时才触发认证逻辑、获取跳转地址,修改代码如下:
模板部分
<a :href="navigationURL" @click="authenticationChoice(currentView['name'])"> <img class="w-12 inline-block align-middle" :src="showAuthenticationIcon(currentView['gitType'])" /> </a>
方法部分
可加重复请求判断避免冗余调用:
authenticationChoice(recieved) { // 相同参数已处理过则直接返回,避免重复发起请求 if (this.$store.state.gitSourceAuthenticationChoice === recieved && this.navigationURL) { return } this.$store.state.gitSourceAuthenticationChoice = recieved; this.$store.dispatch("gitSourceAuthenticationURL").then((response) => { this.navigationURL = response?.oauth2_redirect || ''; console.log(this.navigationURL) }); }
方案2:预先生成跳转链接
如果需要页面加载时就拿到跳转地址,把authenticationChoice的调用放到mounted生命周期或者currentView变化的监听回调中执行,:href直接绑定navigationURL即可。
内容的提问来源于stack exchange,提问作者MEAG
相关产品推荐
相关产品推荐

