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

类式Store中实例化Zustand Store时遇undefined错误求助

问题解决:类式Zustand Store调用setState提示store undefined

问题根源

你直接将this.store.setState赋值给类的setState属性时,丢失了原方法的this绑定——Zustand的setState内部依赖this指向其自身的store实例,当你把它单独提取出来后,调用时this不再指向原store,就会触发store is undefined的错误。

解决方案

方案1:直接调用store实例的setState(最直观)

移除类中单独的setState属性,在方法里直接通过this.store调用setState:

import { create } from 'zustand';

class Store {
  private readonly store;
  public use;

  private get state() {
    return this.store.getState();
  }

  constructor() {
    this.store = create(() => ({ value: 0 }));
    this.use = this.store;
  }

  increment() {
    this.store.setState((state) => ({ value: state.value + 1 }));
  }

  decrement() {
    this.store.setState((state) => ({ value: state.value - 1 }));
  }
}

export const counterStore = new Store();

方案2:手动绑定this到原store实例

在构造函数中用bind方法将setState的this绑定到原store:

import { create } from 'zustand';

class Store {
  private readonly store;
  public use;
  private readonly setState;

  private get state() {
    return this.store.getState();
  }

  constructor() {
    this.store = create(() => ({ value: 0 }));
    this.use = this.store;
    // 绑定this到原store实例
    this.setState = this.store.setState.bind(this.store);
  }

  increment() {
    this.setState((state) => ({ value: state.value + 1 }));
  }

  decrement() {
    this.setState((state) => ({ value: state.value - 1 }));
  }
}

export const counterStore = new Store();

方案3:用箭头函数包裹setState

通过箭头函数捕获原store的上下文,确保setState内部的this指向正确:

import { create } from 'zustand';

class Store {
  private readonly store;
  public use;
  private readonly setState;

  private get state() {
    return this.store.getState();
  }

  constructor() {
    this.store = create(() => ({ value: 0 }));
    this.use = this.store;
    // 箭头函数保留原store的上下文
    this.setState = (...args) => this.store.setState(...args);
  }

  increment() {
    this.setState((state) => ({ value: state.value + 1 }));
  }

  decrement() {
    this.setState((state) => ({ value: state.value - 1 }));
  }
}

export const counterStore = new Store();

内容的提问来源于stack exchange,提问作者João Victor G. Rodrigues

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 19:20:20