vue报错 Error in render: “TypeError: Cannot read properties of undefined (reading ‘nickname‘)“

Cause: I use axios to request data (you can see the data, the request has been successful), and finally load it on the template (the page template has content), but a strange error occurs in the console

The created() hook function requests the interface and reports an error data. Rendering in the DOM element can be rendered normally, but in the developer tool, an error will be reported Error in render: "TypeError: Cannot read properties of undefined (reading 'nickname')"
insert image description here

It means that the function that encapsulates the request interface is called in created, and the obtained data is saved and rendered to the dom element, but before the data is rendered, the dom element will be rendered once to render the obtained data. Then it will cause the data obtained by rendering to be undefined, without this attribute/object.

The popular point is the three-level expression abc, there is no object b in the object a, then reading the value in the object abc will naturally report an error. If it is a two-level expression ab, no error will be reported, and undefined will be returned.

After understanding the reason, I started to check the code and found that there were three layers of expressions in the following vue template code, which was very suspicious, and the error should be here.
insert image description here
reason:

We found that the article here is the data in data, which is displayed by asynchronous calls, and then in the vue rendering mechanism:

Asynchronous data displays the initial data first, and then displays the data with data,

So when the article is loaded, it is still an empty object as follows:
insert image description here
when the rendering is completed, the asynchronous data is loaded.
Therefore, when rendering, the three-layer expression that appears in the article does not exist in the user attribute of the article, and then takes other objects in this object. The value will naturally report an error, but after the rendering is completed, the value in the article is loaded and can be retrieved naturally, which explains why the interface is displayed normally, but the developer tool will report an error

##Solution:
insert image description here
In the place where the request data needs to be loaded to the outermost part of the template, add a v-if to judge whether article.user exists. If it exists, the template will be loaded. If it does not exist, this code will be destroyed. Wait until the data request comes back After that, the template is re-parsed, and the page is loaded, and there is no error in the console [Note, do not use v-show, it does not destroy in the real sense, it is just display and hide on css, and it will still report an error if used]

Guess you like

Origin blog.csdn.net/weixin_44248187/article/details/127897715