javascript - react native : Attempted to assign to readonly property

标签 javascript reactjs react-native javascript-objects

我试图检查该条目是否存在于 AsycStore 中,如果不存在,则创建一个对象并设置它。 并且有一个 return 语句返回数据对象。

这是伪代码-

AsyncStorage.getItem("dataobject").then((do) => {
  if(do == undefined)
  {
    console.log("initializing obj + setting data");
    var dobj = "data object";
    dobj.isdirty = true;
    AsyncStorage.setItem("dataobject",dobj);
  }
  return AsyncStorage.getItem("dataobject");
}).done();
},

我在控制台中收到错误 -

W/ReactNativeJS: 'Error: Attempted to assign to readonly property.\n stack: \n  <unknown>

index.android.bun…:53047\n  tryCallOne                           
index.android.bun…:5094\n  <unknown>                            
index.android.bun…:5160\n  <unknown>                            
index.android.bun…:3399\n  callTimer                            
index.android.bun…:2954\n  callImmediates                       
index.android.bun…:3003\n  <unknown>                            
index.android.bun…:2523\n  guard                                
index.android.bun…:2452\n  __callImmediates                     
index.android.bun…:2523\n  <unknown>                            
index.android.bun…:2503\n  guard                                
index.android.bun…:2452\n  invokeCallbackAndReturnFlushedQueue  index.android.bun…:2501\n URL: http://localhost:8081/index.android.bundle?platform=android&dev=true\n line: 53047\n message: Attempted to assign to readonly property.'

我不太确定我要分配的只读属性是什么。被警告的行号是这一行 - "dobj.isdirty = true";

我不应该向对象添加属性吗?我该如何解决这个问题?正确的做法是什么?

截图-

Attempted to assign to readonly property width=100

最佳答案

您可以通过使用 .catch 来完成此操作,如果那里没有值,则应该抛出异常。像这样的东西:

AsyncStorage.getItem("dataobject")
.then((do) => {
  this.setState({
    myData: do.toJSON();
  })
})
.catch(() => {
   console.log("initializing obj + setting data");
   var dobj = {};
   dobj.isdirty = true;
   AsyncStorage.setItem("dataobject",JSON.stringify(dobj));
});

关于javascript - react native : Attempted to assign to readonly property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33999948/

相关文章:

javascript - Pjax/Ajax 片段在加载时返回 width/offsetWidth 为 0

javascript - 获取白色背景图像中复杂对象的边界(js)

javascript - 有没有办法在 React 应用程序中链接非 React html 文件?

javascript - 为什么我编译文件的时候不能编译样式文件?

javascript - 如何为 flexDirection=row 设置alignSelf

javascript - 如何在 html (php) 文件中加载 javascript 文件

javascript - 将 li 附加到 ul 时遇到问题

javascript - XMLHttpRequest GET 在 React.js 中不起作用

react-native - 中继现代 : how to mock relay for unit testing

android - 如何从 React Native 应用程序创建库