0

I just started out trying mobx-react using stores, and want to use a store plus a single observable, but can't even get this to work.

With @observer, I get the error Uncaught TypeError: Cannot assign to read only property 'render' of object '#<ProxyComponent>'.

Without it, the value becomes 1.

I'm not sure what's going wrong here, any ideas?

import {observable} from 'mobx'
import {inject, observer} from 'mobx-react'

class AppStore {
  @observable value = 1;
}

@inject('store') @observer
class App extends React.Component {
  render(){
    const {store} = this.props
    return (
      <div>
        {store.value}
      </div>
    )
  }
}

const render = (Component) => {
  const appStore = new AppStore()
  ReactDOM.render(
    <AppContainer>
      <Provider store={appStore}>
        <Component/>
      </Provider>
    </AppContainer>,
    document.getElementById('root'),
  )
}

render(App)
David Schumann
  • 9,116
  • 6
  • 56
  • 78
simonzack
  • 16,188
  • 11
  • 62
  • 100

2 Answers2

0

Your code is bit unclear, like from where are you importing Provider and ReactDOM.And also since render is a function used by ReactDOM so the render() function you have defined might conflict with the built in render() function.

And also here it is explained

In general there are three ways in which you can pass stores in MobX

1) Explicitly via props. Easy to test and clear to follow, but can become clumpsy when you have deeply nested structures or many stores (you can solve the latter by having a store for stores)

2) Import stores in the components directly and just use them :) It's the MVP of passing stores around, but stand alone testing of components becomes tricky quickly as you have to make sure your global stores are in the right state first

3) Pass stores around via React's context mechanism. Redux's Provider uses that, as does the mobx-connect package. Context is passed implicitly and deep component can extract data out of the context, but it is still easy to test as you only have to make sure you set up some context before testing the component.

In your case you are using the 3rd point.So I have created a jsfiddle here, where the store is passed as props as in point 1.

pritesh
  • 1,956
  • 15
  • 23
  • Thanks but as you noted, I'm after an answer to mechanism 3. My real code is more involved so 1) is not ideal. – simonzack Jan 17 '18 at 06:20
0

Turns out this was a configuration (webpack hot loader) issue, and not an issue of the code itself (which runs under a jsfiddle).

Adding 'react-hot-loader/babel' to 'plugins' in webpack's 'babel-loader' appears to work.

simonzack
  • 16,188
  • 11
  • 62
  • 100