简体   繁体   English

TypeError:无法分配给 typescript 中的 object '[object Array]' 的只读属性 '0'

[英]TypeError: Cannot assign to read only property '0' of object '[object Array]' in typescript

I am working on angular 8.我正在研究 angular 8。

  1. I have a page that displays a table.我有一个显示表格的页面。 The table displays data from an object array taskList which the component gets as an @Input() .该表显示来自 object 数组taskList的数据,该组件作为@Input()获取。
  2. I have a sorting function on the columns of this table.我对该表的列进行了排序 function。
  3. I also have a delete option on each row.我在每一行上也有一个删除选项。 When I click on the delete option it makes api call to delete the row and then another call to fetch the tasklist array.当我单击删除选项时,它会调用tasklist来删除该行,然后再调用一次来获取任务列表数组。 This is the effect that for the same这是相同的效果
  @Effect()
  DeleteTask$: Observable<Action> = this.actions$.pipe(
    ofType(importActions.DELETE_TASK),
    switchMap(params =>
      this.globalService
        .deleteTask(params)
        .mergeMap(deleteSuccess => {
          return from([
            new importActions.DeleteTaskSuccess(deleteSuccess),
            new importActions.LoadTaskList(),
          ]);
        })
        .catch((error, caught) => {
          return Observable.of(new GlobalError(error));
        }),
    ),
  );

My problem is that the sorting function works fine when I do on first page load.我的问题是当我在第一页加载时排序 function 工作正常。 But if I delete a row and then fetch the tasklist post-delete, I get the following error:但是,如果我删除一行,然后在删除后获取任务列表,则会出现以下错误:

ERROR Error: Uncaught (in promise): TypeError: Cannot assign to read only property '0' of object '[object Array]'
TypeError: Cannot assign to read only property '0' of object '[object Array]'

The as per the error message the following function in my code gives the error根据错误消息,我的代码中的以下 function 给出了错误

  exchange(a, b) {
    const temp = this.taskList[a];
    this.taskList[a] = this.taskList[b]; //this line gives error
    this.taskList[b] = temp;
  }

This function is the part of a sorting code that uses the tasklist array and sorts it.这个 function 是使用tasklist数组并对其进行排序的排序代码的一部分。
The flow being ngOnchanges(detects change is taskList array) calls --> this.taskChange('export_name', 'asc') based on some condition calls --> this. exchange(a, b)ngOnchanges(detects change is taskList array) calls --> this.taskChange('export_name', 'asc') based on some condition calls --> this. exchange(a, b) ngOnchanges(detects change is taskList array) calls --> this.taskChange('export_name', 'asc') based on some condition calls --> this. exchange(a, b)

Following is my ngOnchanges method以下是我的 ngOnchanges 方法

ngOnChanges(changes: SimpleChanges) {
    if (this.taskList !== null && this.taskList !== undefined) {
      this.taskChange('export_name', 'asc');
    }
  }

Following is the main sorting method下面是主要的排序方法

  async taskChange(value, taskOrder) {
    this.sortOrder = taskOrder;
    this.selectedValue = value;
    const expr = {
      asc: (a, b) => a > b,
      desc: (a, b) => a < b,
    };
    for (let i = 0; i < this.taskList.length; i++) {
      for (let j = i + 1; j < this.taskList.length; j++) {
        switch (value) {
          case 'export_name':
            if (
              expr[this.sortOrder](this.taskList[i].name, this.taskList[j].name)
            ) {
              this.exchange(i, j);
            }
            break;
          case 'file_type':
            let type1;
            let type2;
            type1 = this.exportType.transform(this.taskList[i].code, []);
            type2 = this.exportType.transform(this.taskList[j].code, []);
            if (expr[this.sortOrder](type1, type2)) {
              this.exchange(i, j);
            }
            break;
        }
      }
    }
  }

I am not sure what exactly is causing this error when the array changes the second time.当数组第二次更改时,我不确定到底是什么导致了这个错误。 I have tried a bunch of things but none of them worked.我尝试了很多东西,但都没有用。 From what I found online this might be happening because I'm trying to mutate an array received as @Input.从我在网上发现的情况来看,这可能会发生,因为我正在尝试改变作为@Input 接收的数组。 But the above code, which mutates the 'tasklist` array works on initial page load.但是上面的代码,它改变了'tasklist'数组,适用于初始页面加载。 And only stops working when the array changes.并且仅在数组更改时停止工作。 Could someone help me out?有人可以帮帮我吗?

Try creating a copy of the Array before trying to sort it.在尝试排序之前尝试创建数组的副本。 Like using a spread operator.就像使用扩展运算符一样。

arrayForSort = [...this.taskList]

Then after sorting you could assign it back to the taskList field然后排序后,您可以将其分配回 taskList 字段

For those coming to this issue with this error message using React/Redux, it might be that you're trying to mutate state directly which isn't allowed .对于那些使用 React/Redux 遇到此错误消息的人来说,可能是您试图直接改变状态,这是不允许的

In my case I had this setup for getting state within a thunk (simplified):在我的情况下,我有这样的设置,用于在 thunk 中获取状态(简化):

import store from "./myStore";

const state = store.getState();
const getItems = state => state.user.items;
const items = getItems(state);
// ↓ this blew up as it was attempting to manipulate `state`
items.sort((a, b) => a.order - b.order);

This was fixed for me by:这是通过以下方式为我修复的:

import store from "./myStore";

const state = store.getState();
const getItems = state => state.user.items;
// ↓ in my case items is an array, so I create a new array by spreading state here
const items = [...getItems(state)];
// ↓ which means we're not manipulating state, but just our `items` array alone
items.sort((a, b) => a.order - b.order);

I ran into this exact error while working on a nextjs project.我在处理nextjs项目时遇到了这个确切的错误。 I put a findIndex on an array of objects, trying to add a new key-value pair to a specific object of the array when i got this error.我在对象数组上放置了一个findIndex ,当我收到此错误时,试图将新的键值对添加到数组的特定 object。 so i just did this:所以我只是这样做了:

const arrayOfObjects = [...someOtheObj.originalArrayKey]
const index = arrayOfObjects.findIndex((obj)=>{
  // I had some conditions here
})
arrayOfObjects[index] = newValue

Correct正确的

const arrayOfObjects = [...someOtheObj.originalArrayKey]

wrong错误的

const arrayOfObjects = someOtheObj.originalArrayKey

TypeError:无法分配给 object 的只读属性 'statusKnown' '#<object> '<div id="text_translate"><p> 我正在尝试根据我在基于反应 Class 的组件中的道具更新 state 但我收到错误消息</p><blockquote><p> TypeError:无法分配给 object '#' 的只读属性 'statusKnown'</p></blockquote><p> 这是下面的代码</p><pre>componentDidMount(){ this.calClass() } calClass = () =&gt; { console.log(this.props.statusKnown, this.state.active); if (this.props.statusKnown == "deactive") this.setState({ active: false }); else if ((this.props.statusKnown = "active")) this.setState({ active: true }); };</pre><p> 然后在父组件中</p><pre>&lt;Button item={item} categoryID={categoryID} statusKnown={status}/&gt;;</pre><p> 如果反应不允许这件事,那么可能的解决方案是什么?</p></div></object> - TypeError: Cannot assign to read only property 'statusKnown' of object '#<Object>'

ReactJs 类型错误:无法分配给 object 的只读属性“名称”'#<object> '<div id="text_translate"><p> 我正在尝试更改输入的名称属性,因为我的组件的 state 发生了变化。<br> 简而言之,这就是我想要做的。</p><pre> let displayInputElement = ( &lt;input type="text" name = {pips} placeholder="Type your answer here" className=" form-control" /&gt; ); displayInputElement.props.name = "chicken";</pre><p> 但我收到以下错误</p><blockquote><p>类型错误:无法分配给 object '#' 的只读属性“名称”</p></blockquote><p> 请我如何在反应中实现以下目标</p><pre>displayInputElement.props.name = "chicken"; let pips = displayInputElement.props.name; displayInputElement = ( &lt;input type="text" name = "chicken" placeholder="Type your answer here" className=" form-control" /&gt; );</pre></div></object> - ReactJs TypeError: Cannot assign to read only property 'name' of object '#<Object>'

TypeError: 无法分配给 object 的只读属性 'children' '#<object> '<div id="text_translate"><p> 使用 docker 构建的下一个 js 在包含 getServerSideProps package.json 的所有路由中重新加载时进入内部服务器错误</p><ul><li>反应:“17.0.2”</li><li> 下一个:“^11.1.2”</li></ul><p> <strong>在本地</strong>一切正常,如果我<strong>在没有 docker 的情况下部署它</strong>。 但是在我打开网站后使用<strong>docker</strong> 。 如果我使用客户端路由器导航,一切都很好。 但是一旦我重新加载页面,它就会进入内部服务器错误并且不会重建页面<a href="https://i.stack.imgur.com/FCgpe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FCgpe.png" alt="在此处输入图像描述"></a></p><p> 检查 docker 日志后,我发现了这个</p><pre>TypeError: Cannot assign to read only property 'children' of object '#&lt;Object&gt;' at /app/.next/server/chunks/6859.js:792:29 at /app/node_modules/react/cjs/react.development.js:1067:17 at mapIntoArray (/app/node_modules/react/cjs/react.development.js:964:23) at mapIntoArray (/app/node_modules/react/cjs/react.development.js:1004:23) at Object.mapChildren [as map] (/app/node_modules/react/cjs/react.development.js:1066:3) at Head.makeStylesheetInert (/app/.next/server/chunks/6859.js:782:36) at Head.render (/app/.next/server/chunks/6859.js:839:23) at processChild (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3450:18) at resolve (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3270:5) at ReactDOMServerRenderer.render (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3753:22) at ReactDOMServerRenderer.read (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3690:29) at Object.renderToStaticMarkup (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:4314:27) at Object.renderToHTML (/app/node_modules/next/dist/server/render.js:711:41) at runMicrotasks (&lt;anonymous&gt;) at processTicksAndRejections (node:internal/process/task_queues:96:5) at async doRender (/app/node_modules/next/dist/server/next-server.js:1149:38)</pre></div></object> - TypeError: Cannot assign to read only property 'children' of object '#<Object>'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未捕获的类型错误:无法分配给对象“[对象数组]”的只读属性“1” - Uncaught TypeError: Cannot assign to read only property '1' of object '[object Array]' 类型错误:无法分配给对象“[object Array]”的只读属性“0” - TypeError: Cannot assign to read only property '0' of object '[object Array]' 尝试更新对象中的布尔属性的打字稿收到“ TypeError:无法分配为只读属性” - Typescript trying update a boolean property in my object receives “TypeError: Cannot assign to read only property” 未捕获的TypeError:无法分配为只读对象&#39;#的属性&#39;background&#39; <Object> “ - Uncaught TypeError: Cannot assign to read only property 'background' of object '#<Object>' 未捕获的TypeError:无法分配给对象'#<Object>'的只读属性'exports' - Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>' TypeError:无法分配为只读对象“#”的属性“ exports” <Object> 在ReactJS中 - TypeError: Cannot assign to read only property 'exports' of object '#<Object>' in ReactJS TypeError:无法分配给 object 的只读属性 'statusKnown' '#<object> '<div id="text_translate"><p> 我正在尝试根据我在基于反应 Class 的组件中的道具更新 state 但我收到错误消息</p><blockquote><p> TypeError:无法分配给 object '#' 的只读属性 'statusKnown'</p></blockquote><p> 这是下面的代码</p><pre>componentDidMount(){ this.calClass() } calClass = () =&gt; { console.log(this.props.statusKnown, this.state.active); if (this.props.statusKnown == "deactive") this.setState({ active: false }); else if ((this.props.statusKnown = "active")) this.setState({ active: true }); };</pre><p> 然后在父组件中</p><pre>&lt;Button item={item} categoryID={categoryID} statusKnown={status}/&gt;;</pre><p> 如果反应不允许这件事,那么可能的解决方案是什么?</p></div></object> - TypeError: Cannot assign to read only property 'statusKnown' of object '#<Object>' ReactJs 类型错误:无法分配给 object 的只读属性“名称”'#<object> '<div id="text_translate"><p> 我正在尝试更改输入的名称属性,因为我的组件的 state 发生了变化。<br> 简而言之,这就是我想要做的。</p><pre> let displayInputElement = ( &lt;input type="text" name = {pips} placeholder="Type your answer here" className=" form-control" /&gt; ); displayInputElement.props.name = "chicken";</pre><p> 但我收到以下错误</p><blockquote><p>类型错误:无法分配给 object '#' 的只读属性“名称”</p></blockquote><p> 请我如何在反应中实现以下目标</p><pre>displayInputElement.props.name = "chicken"; let pips = displayInputElement.props.name; displayInputElement = ( &lt;input type="text" name = "chicken" placeholder="Type your answer here" className=" form-control" /&gt; );</pre></div></object> - ReactJs TypeError: Cannot assign to read only property 'name' of object '#<Object>' ReactJs - TypeError:无法分配给对象“#”的只读属性“transform”<Object> &#39; - ReactJs - TypeError: Cannot assign to read only property 'transform' of object '#<Object>' TypeError: 无法分配给 object 的只读属性 'children' '#<object> '<div id="text_translate"><p> 使用 docker 构建的下一个 js 在包含 getServerSideProps package.json 的所有路由中重新加载时进入内部服务器错误</p><ul><li>反应:“17.0.2”</li><li> 下一个:“^11.1.2”</li></ul><p> <strong>在本地</strong>一切正常,如果我<strong>在没有 docker 的情况下部署它</strong>。 但是在我打开网站后使用<strong>docker</strong> 。 如果我使用客户端路由器导航,一切都很好。 但是一旦我重新加载页面,它就会进入内部服务器错误并且不会重建页面<a href="https://i.stack.imgur.com/FCgpe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FCgpe.png" alt="在此处输入图像描述"></a></p><p> 检查 docker 日志后,我发现了这个</p><pre>TypeError: Cannot assign to read only property 'children' of object '#&lt;Object&gt;' at /app/.next/server/chunks/6859.js:792:29 at /app/node_modules/react/cjs/react.development.js:1067:17 at mapIntoArray (/app/node_modules/react/cjs/react.development.js:964:23) at mapIntoArray (/app/node_modules/react/cjs/react.development.js:1004:23) at Object.mapChildren [as map] (/app/node_modules/react/cjs/react.development.js:1066:3) at Head.makeStylesheetInert (/app/.next/server/chunks/6859.js:782:36) at Head.render (/app/.next/server/chunks/6859.js:839:23) at processChild (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3450:18) at resolve (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3270:5) at ReactDOMServerRenderer.render (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3753:22) at ReactDOMServerRenderer.read (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:3690:29) at Object.renderToStaticMarkup (/app/node_modules/react-dom/cjs/react-dom-server.node.development.js:4314:27) at Object.renderToHTML (/app/node_modules/next/dist/server/render.js:711:41) at runMicrotasks (&lt;anonymous&gt;) at processTicksAndRejections (node:internal/process/task_queues:96:5) at async doRender (/app/node_modules/next/dist/server/next-server.js:1149:38)</pre></div></object> - TypeError: Cannot assign to read only property 'children' of object '#<Object>'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM