MobX makeAutoObservable does not create actions

40 Views Asked by At

I have a MobX-Store setup with makeAutoObservable(this). I would expect this to mark the methods that write to observable state as actions. Yet that does not seem to be the case. Here's what I did:

I created the following class:

class ModalState {

  opened = false

  constructor() {
    makeAutoObservable(this)
  }

  open() {
    this.opened = true
  }
}

let modalState: ModalState

export function getModalState() {
  if (!modalState)
    modalState = new ModalState()
  return modalState
}

Then I try to use it to control my modal like this:

const MyModal = observer(() => {

  const [modalState] = useState(() => getModalState())

  return (
    <Modal opened={modalState.opened} onClose={modalState.close}>
      ...
    </Modal>
  )
})

However, this invocation of modalState.close does not count as an action, which I know because the modal does not actually close when I click the close button. To fix it, I have to change the class like this:

const MyModal = observer(() => {

  const [modalState] = useState(() => getModalState())

  const close = action(() => modalState.close())
  return (
    <Modal opened={modalState.opened} onClose={close}>
      ...
    </Modal>
  )
})

Which works, but then what is the point of makeAutoObservable? I thought I could mark methods of the store as actions, so that I can then use them as normal in the rest of my code without having to wrap them in actions every time I want the store to change.

Is there a way to make actions on a store invokable directly, like the first version of MyModal?

0

There are 0 best solutions below