8

I have a Store:

class Store {
  user!: User;

  constructor() {
    makeObservable(this, {
      user: observable,
      setUser: action
    });
  }
  
  setUser = (user: User | undefined) => this.user = user;
}

And I'm getting this error: Error: [MobX] Cannot apply 'observable' to 'Store@user': Field not found.

User is a custom object, should I treat him differently (observable wise)?

Thanks in advance!

gran33
  • 12,421
  • 9
  • 48
  • 76
  • If your question has been answered, please make sure to accept an answer for further references. – Danila Aug 04 '21 at 12:39

1 Answers1

15

By default make(Auto)Observable only supports properties that are already defined, so you need to define user inside constructor or make it nullable like that: user: User | null = null.

Alternatively you might want to try to reconfigure how class properties initialisation works, using useDefineForClassFields TS compiler flag:

"compilerOptions": {
  "useDefineForClassFields": true
},
Danila
  • 15,606
  • 2
  • 35
  • 67