如何通过回调将值返回到使用 jquery 的 $.ajax 计算的 mobx 中?

问题描述

在我的项目中,我有以下 mobx 商店:

class AvailabilityCallendar {
  @observable selected_date = new Date();
  @observable max_persons = 2;
  @observable loading = false;

  @computed get availableDates() {
    $.ajax({
      url:
        createUrl('/calendar/availability') +
        'persons=' +
        this.max_persons +
        '&' +
        selected_date.format('yy-m-d'),type: 'GET',beforeSend: function () {
        this.loading = true;
      },success: function (data) {
        // return value here
      },fail: function (jqXHR,textStatus,errorThrown) {
        this.loading = false;
        console.error('Error: ' + errorThrown + ',Status: ' + textStatus);
      },});
  }
}

在这种情况下,我想知道如何从成功 ajax 回调中返回值。 你知道怎么做吗?

解决方法

您可以在此处返回 Promise,但我不建议这样做,因为您违反了计算值的规则。

计算不应该有副作用,也不应该更新其他可观察值。

, mobx 的

computed 值是其他可观察元素的“视图”。它必须是同步操作,因此您的实现不正确。

您需要做的是一个简单的 observable 和一个将更新其值的异步方法。

// pseudo code

class AvailabilityCallendar {
  @observable selected_date = new Date();
  @observable max_persons = 2;
  @observable loading = false;
  @observable availableDate = null; // initial value,it may be any valid js value.

  async getAvailableDate() {
    $.ajax({
      url:
        createUrl('/calendar/availability') +
        'persons=' +
        this.max_persons +
        '&' +
        selected_date.format('yy-m-d'),type: 'GET',beforeSend: function () {
        this.loading = true;
      },success: function (data) {
        this.availableDate = data // this assignment will trigger all the observers of the observable field.
      },fail: function (jqXHR,textStatus,errorThrown) {
        this.loading = false;
        console.error('Error: ' + errorThrown + ',Status: ' + textStatus);
      },});
  }
}

然后调用 getAvailableDate()