2
votes

I am trying to update counter whoch observable variable, and watch the values in component, swhen I click the increment button, this.counter is NaN always and couldnt understand why. component:

@observer
class App extends Component {
  constructor(props){
    super(props)
  }
  render() {
    const counter = this.props.appState;
    return (
        <div className={styles.description}>
          <button onClick={counter.increment.bind(this)}>+</button>

Mobx class;

class AppState{
    @observable counter=0

   increment(){
       debugger //its null..
        this.counter++;
    }
}
export default AppState

mainjs:

import AppState from './AppState'
...
var appState = new AppState

ReactDOM.render(
  <App appState={appState}/>,
  document.getElementById('root')
);

how can I fix it ?

1

1 Answers

2
votes

I think your issue is that you need to keep a sharp tongue when it comes to what this refers to. There's no counter field in App, and that's what you end up trying refer to when you write bind(this).

Try <button onClick={() => counter.increment()}>+</button>.