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

Vue3 Pinia中setBalance后init方法内balance值为null问题

问题原因与解决方案

你的代码核心问题是变量名作用域冲突,导致Pinia Store内部的balance ref未被正确赋值。

具体分析

在UseBaseStore的setBalance函数中,你将参数命名为balance,这与外部定义的const balance = ref(null)重名了。在函数作用域内,参数的优先级高于外部变量,因此setBalance里的balance指向的是传入的普通对象参数,而非内部的ref变量。

执行balance.value = balance时,实际是给这个普通参数对象新增了一个value属性,值为对象本身——这就是为什么第一个console.log(balance.value)能输出预期对象,但内部的ref变量balance始终是初始的null,所以init函数中的打印结果为null。

修复方案

只需要修改setBalance的参数名,消除变量名冲突即可:

import {defineStore} from "pinia";
import {ref} from "vue";
export const UseBaseStore = defineStore('BaseStore', () => {
    const balance = ref(null)

    // 将参数名改为newBalance,避免与内部ref变量重名
    function setBalance(newBalance) {
        balance.value = newBalance
        console.log(balance.value)
    }

    function init() {
        console.log(balance.value)
    }

    return {balance, setBalance, init}
})

也可以选择重命名内部的ref变量(比如改为_balance),核心是确保函数作用域内不会出现同名变量覆盖的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 13:59:55