当填充 JSON-Object 时,Mobx 无法设置未定义的属性“@observable”

问题描述

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

这是发生问题的 Axios 调用

/opt/jboss/keycloak/themes/raincatcher-theme

这部分 @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

为什么我不能将带有图像对象的数组分配给这个 observable?这让我觉得很困惑。

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

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

解决方法

当您在 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);
              });