What are some ways to make autorun compatible with runInAction in mobx?

Currently delving into the world of mobx and runInAction, facing a challenge in comprehending why autorun fails to trigger my callback in this particular scenario:

class ExampleClass {

    // constructor() {
    //     this.exampleMethod();
    // }

    @observable myBoolean = false;

    async exampleMethod() {

        await new Promise(resolve => setTimeout(resolve, 1000));
        runInAction(() => this.myBoolean = true); // <--- myBoolean: true never gets logged to the console. why?
        await new Promise(resolve => setTimeout(resolve, 3000));
        runInAction(() => this.myBoolean = false); // <--- still not being logged
    }
}

let example = new ExampleClass();

example.exampleMethod();
autorun(() => console.log("myBoolean:", example.myBoolean));

Employing TypeScript and babel alongside decorators.

My understanding dictates that runInAction(...) aids in modifying observables when outside of an action-marked method?

What could be causing the malfunction in my script?

Answer №1

If you are working with MobX version 6, there have been some changes to the API. Now, in order to properly utilize it, you must include either makeAutoObservable or makeObservable within the constructor like this:

import { autorun, makeAutoObservable, observable, runInAction } from 'mobx';

class FooClass {
  constructor() {
    makeAutoObservable(this);

    autorun(() => console.log('myBool:', this.myBool));
    this.fooMethod();
  }

  // If you use `makeAutoObservable`, you can actually remove the decorator here
  @observable myBool = false;

  async fooMethod() {
    await new Promise((r) => setTimeout(r, 1000));
    runInAction(() => (this.myBool = true)); // This will be logged now
    await new Promise((r) => setTimeout(r, 3000));
    runInAction(() => (this.myBool = false)); // This will also be logged now
  }
}

new FooClass();

Check out the example on Codesandbox

For more information, refer to the official documentation

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am currently in the process of cross-referencing the tags that have been retrieved with those that have been selected or created. If a tag does not exist

I have a collection of tags in an object, and I want to dynamically add new tags before submitting the form. Despite using vue watch, it doesn't seem to be working for me. Here is the code snippet: data() { return { blog: { blog_ti ...

What is the best way to restrict the input year on @mui/x-date-pickers to a certain range?

Is there a way to restrict the input year range when using @mui/x-date-pickers? I want to limit it from 1000 to 2023 instead of being able to enter years like 0000 or 9999. https://i.stack.imgur.com/0p6j3.jpg I have tried adding a mask to InputProps in my ...

Utilize jQuery to track and record AdWords conversions

I have noticed a number of inquiries regarding tracking Adwords conversions with jQuery on this platform. However, it appears that there is no definitive solution yet. My attempt at recording a conversion involves the code below following the submission o ...

"Positioned at the top of the page is the alert box, with the

I'm looking to add an alert at the top of my webpage containing a form for visitors to enter their phone number. Currently, I have a "alert alert-info" div with the form inside it placed at the top of my body tag, which works perfectly. However, when ...

AngularJs input field with a dynamic ng-model for real-time data binding

Currently facing an issue with my static template on the render page. <form name="AddArticle" ng-submit="addArticle()" class="form add-article"> <input type="text" value="first" init-from-form ng-model="article.text[0]" /> <input typ ...

Send properties to the component container

I am currently working on a higher order component that toggles between two children - a component that renders data and a loading component. The challenge I am facing is how to pass the loading state from the data component to the HOC for conditional rend ...

Is there a way to send URL variables to express.js similar to how it's done in PHP?

Currently in the process of converting my PHP website to Express.js. There are numerous scripts on my frontend that generate links in the format page.php?id=10&something=anything. Is there a way in Express.js to capture variables from URLs structured ...

How to fetch images from a database in CodeIgniter by utilizing JSON and AJAX functions?

Trying to retrieve an image using ajax/json format for the first time, all variables are displaying except the image. The name of the image is visible when inspecting the element in the browser and it is saving correctly into the image folder. I need help ...

Assign object properties to a constant variable while validating the values

When receiving the features object, I am assigning its values to constants based on their properties. const { featureCode, featureSubType, contentId, price, family: { relationCountsConfig: { motherCount, fatherCount, childrenCount }, max ...

React Scroll and Material-UI button active link not functioning correctly

Whenever the link goes to the correct page, I want to add a special background effect or change the font color. Despite trying to use CSS for this purpose, it didn't work as intended. If you want to take a look at my code on codesandbox, follow this ...

How to verify the parent nodes in a jstree

I have implemented a two state jstree. However, I am encountering an issue where it is not possible to select any other node in relation to a node. My goal is that when I click on a specific node, all of its parent nodes should also be checked. Any assist ...

Upon transitioning from typescript to javascript

I attempted to clarify my confusion about TypeScript, but I'm still struggling to explain it well. From my understanding, TypeScript is a strict syntactical superset of JavaScript that enhances our code by allowing us to use different types to define ...

utilizing javascript once form elements are dynamically inserted

While dynamically constructing form elements, I encountered an issue with generating unique IDs when the form is submitted. Everything works fine except for the JavaScript function responsible for populating the year in a dropdown selection. The issue ari ...

Retrieve information from api and showcase it in html

Recently, I came across an interesting API file that caught my attention: My goal is to extract information from this API and present it on a HTML page in a visually appealing format. Despite scouring various forums, I have yet to find a solution that fi ...

Removing data based on various criteria in Prisma

While I understand that the where clause in Prisma requires a unique input for its delete operation, I have utilized the @@unique function to ensure that multiple conditions need to be columns together and must be unique. However, I am struggling with how ...

Exploring the Potential of Using ngIf-else Expressions in Angular 2

Here is a code snippet that I wrote: <tr *ngFor="let sample of data; let i = index" [attr.data-index]="i"> <ng-container *ngIf="sample.configuration_type == 1; then thenBlock; else elseBlock"></ng-container> <ng-template #t ...

Oops! The Route.get() function in Node.js is throwing an error because it's expecting a callback function, but it received

Currently, I am learning how to create a web music admin panel where users can upload MP3 files. However, I have encountered the following errors: Error: Route.get() requires a callback function but received an [object Undefined] at Route. [as get] (C:&bso ...

Directing users to varying pages based on a particular criteria

As we continue to develop our application, we are creating various pages and need to navigate between them. Our current framework is Next.js. The issue we are facing involves the Home page: when transitioning from the Home page to another page (such as pa ...

Angular is encountering a circular dependency while trying to access a property called 'lineno' that does not actually exist within the module exports

I am working on an Angular project and using the Vex template. My project utilizes Angular 9 and Node.js v15.2.0. Every time I run the project with the command ng serve -o, it displays a warning message. https://i.stack.imgur.com/8O9c1.png What could b ...

Why is it that a static variable cannot be accessed using the `this` keyword in a static method when the static method is called in any route's controller in NODEJS?

Is it possible to access static variables in a static method using the 'this' keyword? The answer is yes, but there seems to be an issue when passing that static method in any route. The 'this' keyword refers to the class, yet its value ...