【问题标题】:Mobx cannot set property '@observable' of undefined when filled with JSON-Object用 JSON-Object 填充时,Mobx 无法设置未定义的属性“@observable”
【发布时间】:2021-05-12 08:07:34
【问题描述】:

我在将 JSON-Image-Files 保存到 mobx observables 时遇到问题,如下所示。

这是发生问题的 Axios 调用:

 @observable images = [];
 @action getAllImages() {
    const payload = {
      "token": getTokenFromLocalStorage
    }

            axios.get(API_BASE_URL + '/user/images', payload)
              .then(function(response) {
                if (response.status >= 200 && response.status < 300) {
                  console.log("RESPONSE IMAGE:" + JSON.stringify(response.data.files, null, 2));
     >>               this.images = response.data.files;
                  console.log("IMAGESTORE IN AXIOS " + this.images[0]);
                } else {
                  alert("error getting images");
                }
              })
              .catch(function(error) {
                console.log("DOWNLOAD: " + error);
              });
  }

这部分this.images = response.data.files;抛出异常:Cannot set property 'images' of undefined

上面一行的输出:

RESPONSE IMAGE:[
  "img_1612801479594.jpg",
  "img_1612802187709.jpg",
  "img_1612802491363.jpg",
  "img_1612803744426.jpg"
]

为什么我不能将带有 Image-Objects 的数组分配给这个 observable?这让我感到很困惑。

这是我发送 JSON 响应的 Node-JS 后端:

router.get("/images", function(req, res) {
  // Sends all available images
  let sendFiles = [];
  let files = fs.readdirSync(imagePath);
  files.forEach(file => {
    if (file.includes("jpg") ||
        file.includes("jpeg") ||
        file.includes("JPEG") ||
        file.includes("png") ||
        file.includes("PNG")) {
      sendFiles.push(file)
    }
  });
  res.send({files: sendFiles});
});

【问题讨论】:

    标签: json reactjs rest axios mobx


    【解决方案1】:

    当您在 then 或 catch 中编写函数处理程序时,它们将有自己的上下文。对于下面的代码,

    this.images = response.data.files;
    

    'this',指的是'then'函数的上下文。它不会在该函数中声明“图像”。

    如果您使用 es6,只要您声明了“图像”,下面的代码就可以工作

    axios.get(API_BASE_URL + '/user/images', payload)
          >>        .then((response) => {
                    if (response.status >= 200 && response.status < 300) {
                      console.log("RESPONSE IMAGE:" + JSON.stringify(response.data.files, null, 2));
         >>               this.images = response.data.files;
                      console.log("IMAGESTORE IN AXIOS " + this.images[0]);
                    } else {
                      alert("error getting images");
                    }
                  })
        >>          .catch((error) => {
                    console.log("DOWNLOAD: " + error);
                  });
    

    【讨论】:

      猜你喜欢
      • 2021-11-27
      • 1970-01-01
      • 2019-07-14
      • 2022-10-30
      • 2023-02-10
      • 1970-01-01
      • 1970-01-01
      • 2015-12-07
      相关资源
      最近更新 更多