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

Svelte store的subscribe()为何在值未变更时触发?

Svelte Store订阅函数在值未变更时重复触发的原因

问题背景

我定义了一个Svelte的可写Store activeAccountIndexStore,代码如下:

export const activeAccountIndexStore: Writable<number | "native" | null> = writable(null);

它的初始值是null,在完成部分网络请求后,会被设置为具体数字或字符串'native'。

同时我封装了一个订阅方法,供其他组件调用:

export const onChangeActiveAccount = (activeAccountHandler: ActiveAccountHandler) => {
  activeAccountIndexStore.subscribe((newValue) => {
    log(`➡️➡️➡️➡️➡️ activeAccountIndexStore new value`, newValue);
    if (newValue !== null) {
      const activeAccount = getActiveAccount();
      activeAccountHandler(activeAccount);
    }
  });
};

异常现象

实际运行中发现,即使Store的值没有发生变化,订阅的处理函数仍会被重复调用,日志输出如下:

stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value null
stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value null
stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0
stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0
stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0
stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0
stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0

MDN的Svelte文档说明:

A store is an object with a subscribe() method that allows interested parties to be notified whenever the store value changes.

按照文档描述,只有当Store的值发生变化时才会触发订阅通知,但现在的情况明显不符合预期。我原本预期的日志应该是:

stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value null
stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0

疑问

为什么Svelte Store的subscribe()会在值未变更时重复触发?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 06:05:19