Mobx 可观察数组

Mobx Observable Array

我被这个讨厌的错误困住了。我有一个 Observable 数组,我正在使用 Axios Get 请求填充它。

getVirtualMachines(){
    request.get('/Home').then(response => {
       console.log(response.data[0].name);
        this.virtualMachines = response.data;
    }).catch(error => {
        console.log(error);
    })
} 

Observable Array 看起来像

@observable virtualMachines: [{
    id: string,
    ip: string,
    name: string,
    power: string,
    sku: string
}]; 

我叫这个uisngcomponentWillMount(){ this.props.store.getVirtualMachines(); }

现在在渲染方法中我是这个

let vms: VirtualMachine[] = this.props.store.virtualMachines;
console.log(vms);

到目前为止一切顺利。现在我正在尝试使用 slice() 映射 Vms 数组以将可观察数组转换为普通数组,并且我在错误

之后得到错误
render(){
let vms: VirtualMachine[] = this.props.store.virtualMachines;
console.log(vms.slice());
....
....
}

Uncaught TypeError: Cannot read property 'slice' of undefined

warning.js:33 Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

我只用了 slice 方法

console.log(vms.slice());

您的第一个渲染中没有 virtualMachines 数组。你可以这样做,给你的数组一个空数组的默认值:

class Store {
  @observable virtualMachines: [{
    id: string,
    ip: string,
    name: string,
    power: string,
    sku: string
  }] = [];

  getVirtualMachines(){
    request.get('/Home').then(response => {
      this.virtualMachines.replace(response.data);
    }).catch(error => {
      console.log(error);
    });
  } 
}