antd 不允许 Mobx 在操作之外更改观察到的可观察值

Mobx changing observed observable values outside actions is not allowed issue with antd

我想将文件上传到服务器并获得响应,但是如果我覆盖 Upload 组件的 onChange 属性(来自 antdmobx开始出错,文件上传卡在 uploading 状态(这实际上是一个常见的 issue,但它是中文的,没有 mobx 示例):

Error: [mobx] Since strict-mode is enabled, changing observed observable values outside actions is not allowed. Please wrap the code in an action if this change is intended.
Tried to modify: UploadComponent@83.fileList[..].percent
...

Tried to modify: UploadComponent@83.fileList[..].status

代码:

@observer
export class UploadComponent extends Component<{}, {}> {
  @observable fileList: UploadFile[]

  @action
  handleChange = (info: UploadChangeParam) => {
    const fileList = [...info.fileList]
    fileList.map(file => {
      if (file.response) {
        // do somethong with response
      }
      return file
    })
    this.fileList = fileList
  }

  render() {
    return (
      <Upload
        action={"http://localhost:5000/send-file/"}
        accept=".pdf"
        onChange={this.handleChange}
        fileList={this.fileList}
      >
        <Button>
          <Icon type="upload" /> Upload file
        </Button>
      </Upload>
    )
  }
}

但是我有点困惑,因为我在 action.

中包装了 handleChange 方法

这是使用 mobx 和异步事件时的常见错误。

动作包装器/装饰器只影响当前运行函数,而不影响当前函数调度(但未调用)的函数。 最简单的解决方案是使用 runInAction 函数

试试这个

@action
handleChange = (info: UploadChangeParam) => {
  runInAction(() => {
    const fileList = [...info.fileList]
    fileList.map(file => {
      if (file.response) {
        // do somethong with response
      }
      return file
    })
    this.fileList = fileList
  })
}

更多信息可以参考官方文档:Writing asynchronous actions

是的,试试这个 runInAction

@action addNewtorkListener = async () => {
            this.isNetworkOnline=true;
    
            Network.addListener('networkStatusChange', (status) => {
                debugger
                runInAction("loading activities", () => {
                if (!status.connected) {
                    this.isNetworkOnline=false;
                    toast.error("İnternet Bağlantısı Bulunamadı.");
                    toast.info("Offline Yapılan işlemler offline menüsünden senkronize edilebilir.");
                } else {
                    this.isNetworkOnline=true; 
                    toast.success("İnternet Bağlantısı Sağlandı.");
                }
           
            });
        });