Error: [MobX] Cannot apply 'observable' to 'Store@user': Field not found

Viewed 3206

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!

1 Answers

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
},
Related