Reputation: 2781
import React from "react"
import { observable } from "mobx";
import { observer } from "mobx-react"
import { computed, action } from "mobx"
@observer
export default class Dice extends React.Component {
@observable
value = 1;
@computed
get result() {
return this.value > 3 ? "YOU WIN" : "YOU LOSE"
}
@action
handleRoll = () => {
this.value = Math.floor(Math.random() * 6) + 1
}
render() {
return (
<div>
<br />
<button onClick={this.handleRoll}>Roll Dice</button> <br />
<p>The value is {this.value}</p>
<p>{this.result}</p>
</div>
)
}
}
Now, i have used the action decorator for handleRoll function. I used it because my original state is changed i.e value will change everytime (most probably) as i click on roll dice button.Now even when i removed the action decoartor then still every things works fine with no errors . Now the question is if we can accomplish the task of changing the state then why to use actions at all ?
Upvotes: 1
Views: 235
Reputation: 8848
By default using actions is not required to change state in mobx, but it's a [good best practice in larger codebases|https://mobx.js.org/refguide/action.html#when-to-use-actions]. If you enable strict mode, mobx will throw an error if you try to modify state outside of an action.
To enable strict mode in mobx 4.0.0 and newer, use mobx.configure({enforceActions: true})
. In older versions of mobx this was accomplished with mobx.useStrict(true)
.
Upvotes: 1