reactjsmobxmobx-react

mobx observable field for class type isn't working


I am using MobX 6+ in my project and I have a class with an @observable annotated field that contains class type. I initialize the type with:

class MyClass {

    @observable myObservableField = ClassToInitialize;


    problemHere() {

         ....

         const MyType = this.myObservableField;
         const TypeInstance = new MyType(); // <-- Error is thrown at this line

         ....
    }
}

class ClassToInitialize {
     constructor() {
         ....
     }
}

However I get the following error:

Uncaught TypeError: Class constructor IgnoreRegion cannot be invoked without 'new'

Solution

  • After investigating the issue, it appears to happen due to MobX wrapping the field in a proxy function.

    In order to solve the issue, use shallow:

    class MyClass {
    
        @observable.shallow myObservableField;
        ....
    }