Skip to content

Error #3: No access to ViewModelStore

This happened because the viewModels param is not provided when creating a ViewModelBase instance.

Explanation:

This can happen if you override or implement the createViewModel() method in your custom ViewModelStore or ViewModelStoreBase and forget to pass the viewModels param to the ViewModel creation params.

ts
import {
  ViewModelStoreBase,
  ViewModel,
  ViewModelCreateConfig
} from 'mobx-view-model';

export class ViewModelStoreImpl extends ViewModelStoreBase {
  constructor(protected rootStore: RootStore) {
    super();
  }

  createViewModel<VM extends ViewModel<any, ViewModel<any, any>>>(
    config: ViewModelCreateConfig<VM>,
  ): VM {
    const VM = config.VM;
    const yourCustomConfig = {
      ...config,
      viewModels: undefined,
    }
    return new VM(yourCustomConfig);
  }
}

config argument in createViewModel method already should has viewModels property

Because it gets passed from <ViewModelsProvider />
Otherwise it will be undefined

Potential solution

1. Add ViewModelsProvider

Use <ViewModelsProvider /> to pass viewModels for all created VM instances in React.

Example:

tsx
export const App = () => {
  return <ViewModelsProvider value={vmStore}>...</ViewModelsProvider>;
};

2. Check your custom createViewModel() implementation

Check that you pass the viewModels param to the ViewModel creation params.

Released under the MIT License.