Mobx - 对象文字只能指定已知属性

Mobx - Object literal may only specify known properties

我最近开始学习如何使用 Mobx 来管理我的应用程序的状态,最近我遇到了以下错误:

Object literal may only specify known properties, and "data" does not exist in type "AnnotatiosMap<this, never>".

每当我想将我的 class 的 属性 设为私有时,就会发生这种情况。但是,如果它是 public 或受保护,则不会出现此问题。

这是我的一小段代码:

import { makeObservable, observable } from "mobx";

class Base {
  private data: string[];

  constructor() {
    this.data = [];

    makeObservable(this, {
      data: observable,
    });
  }

  public getData = (): string[] => {
    return this.data;
  };

}

export default new Base();

我应该怎么做才能使我的 属性 私密但仍被监视?

祝你有愉快的一天!

From the docs:

By default TypeScript will not allow you to annotate private fields. This can be overcome by explicitly passing the relevant private fields as generic argument, like this: makeObservable<MyStore, "privateField" | "privateField2">(this, { privateField: observable, privateField2: observable })