This is the 16th day of my participation in Gwen Challenge

Lynne, a front-end development engineer who can cry, love and laugh forever. In the Internet wave, love life and technology.

preface

A while ago encountered a Bug…..

Error: [nuxt] Error while mounting app: HierarchyRequestError: Failed to execute 'appendChild' on 'Node':
This node type does not support this method. at some-file.js:1
Copy the code

The investigation lasted for more than 2 hours. If we want to investigate the root cause, we found this article and explained it perfectly.

The original address: Vue activation failed (blog. Lichter. IO/posts/Vue – h…

Server-side rendering has many benefits, especially when a site like Nuxt.js or GridSome is a breeze to develop vuE-SSR applications, whether using dynamic SSR or generating static sites. On the other hand, server-side rendering can introduce complexity and errors we’ve never seen before. While most of the errors were documented and workarounds were provided, one error left many confused: Vue activation failed.

What is Vue activation failure

Activation is the process when Vue transforms the server to render the markup and make it react, thus making it reflect Vue changes. If the Vue expects a different tag than the rendered HTML, an activation failure occurs.

Vue-ssr explains the process by which the Vue takes over static HTML tags sent by the server on the browser side and turns them into a dynamic DOM managed by the Vue.

Understanding: The server has rendered the HTML. Instead of discarding it and recreating all the DOM elements, it deactivates the rendered static HTML and makes it dynamic in response to subsequent data changes.

SSR + client mix – The browser will change some of the special HTML structures, causing them to mismatch the virtual DOM structure generated by Vue.

How to identify activation failure

We now realize what an activation is and when it fails, but how do we as developers find out that an activation doesn’t work as expected? There are two error messages that will definitely indicate that the activation failed but both have limitations.

1. The first is only in development, no matter which mode:

Parent: <div class="container"> client-hook-3.js:1:16358 Mismatching childNodes vs. VNodes: NodeList(3) [p, p, p] Array [{...}] [Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render.Copy the code
  1. The second error message is only in production and statically generated sites:
Error: [nuxt] Error while mounting app: HierarchyRequestError: Failed to execute 'appendChild' on 'Node':
This node type does not support this method. at some-file.js:1
Copy the code

As we all know, activation only happens when the page is first rendered by the server, so it’s usually only in your application’s initialization request.

(asyncData and data – data on the client is mixed with data in asyncData)

Because activation failures are not visible when navigating through a TAB but only when hard reloading, this makes it more difficult to find activation failures.

So activation errors are sometimes found only in hierarchical systems or, worse, only in production environments. In rare cases, errors are not even printed and some components simply stop working.

Three, the general cause of the error

Now that we know how to spot activation errors, we’ll examine the typical causes of Vue activation errors. Of course, we can’t cover all possible causes, because they vary widely and depend on your code.

In the following sections, every time server-side rendering is mentioned, it is relevant to both cases (dynamic SSR and static site generation) because technically both have server-side rendering content. (unless otherwise stated)

1. Unreasonable HTML

Incorrect HTML is the first place you should check when an activation failure occurs, and this should also be an error message:

This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>
Copy the code

Unfortunately, bad HTML is not usually the cause of activation failures. However, you should double check your marks. Also, be sure to check the miniaturization Settings, as excessive HTML miniaturization can result in invalid HTML. If you have user-generated output or content from your CMS, it is worth verifying that this content is also valid HTML. Finally, third-party plug-ins or services can also affect and manipulate HTML. A common example of the latter is Cloudflare, when you enable their services. Such as HTML miniaturization, Rocket Loader, or other features that change page content.

I created a simple example CodeAndBox that contained invalid HTML and triggered an activation failure.

2. Modify the HTML script

About scripting: If you insert third-party JS files into your Vue application, you can also change the HTML before the Vue receives and activates the HTML from the server

3. The status of the server and client is different

Inconsistent states on the server and client are the most common cause of activation failures. As usual, the reasons for the inconsistencies vary widely.

1) Date, timestamp, and randomization

When your site contains a date or time stamp, be careful and make it as static as possible, especially if your site is statically generated. If the client evaluates an expression like new Date(), the expression may be different from the Date generated when the same Date was retrieved during the development phase on your server. It also confused me about the company’s “About” page, where I wanted to sort the people displayed by the current minute.

export const deterministicRotate = (arr) = > {
  if (arr.length <= 1) {
    return arr
  }
  const rotations = (new Date()).getMinutes() % arr.length
  return rotations ? arr : arr.reverse()
}
Copy the code

If the user opens the page at an odd time, plan to reverse the array. This works well when using dynamic SSR. But this feature becomes a Bug when switching to a statically generated JAMstack site. You can click the link to refresh a minute later and see that the name and person have been swapped correctly, but the image is the same as before. Oh, no! This is due to a server and client time mismatch. Work returns to normal after removing the uncertain shuffle code.

2) authorized

Another common reason for inconsistencies is user authentication. This applies to both dynamic SSR and static site generation.

The server “does not know authentication” when authentication status is stored only on the client (for example, in localStorage). This inevitably leads to activation problems because the server and client information are fundamentally different at login time. Therefore, if the server does not know the authentication status of your page being statically generated, no authentication-related components should be rendered on the server side.

You might wonder why it always works for static web sites: Because when you generate a web site, it’s HTML, and serialized code is “stateless.” During the construction phase, we cannot consider “logged in user state.” This means that you must exclude all authentication-related components from rendering on the server.

3) Other reasons

In addition to these two cases, there are many more edge cases that can strike you and cause inconsistencies. We will resolve activation errors even if they are not listed here! First, we narrow it down to the DOM element that is causing the problem.

Solve the problem of activation failure

1. Discover the element that causes the activation failure

We can use devTools on your favorite browser to narrow the problem down to a specific component or DOM element.

1) Make sure you’re in a development environment

2) Open the development debugging tool

3) Trigger activation warnings (usually by reloading web pages)

4) Expand [Vue Warn] The client side… Error message view trace stack (depending on browser, also open pop-up VueJS list)

5) Clicking on an activation callback will open the source code for the Vue activation function

6) Now, whenever this function returns false, a debugger is set, which happened three times while writing text:

if(process.env.NODE_ENV ! = ='production') {
  if(! assertNodeMatch(elm, vnode, inVPre)) {return false //HERE}}if(process.env.NODE_ENV ! = ='production' &&
          typeof console! = ='undefined' &&
          !hydrationBailed
    ) {
        hydrationBailed = true;
        console.warn('Parent: ', elm);
        console.warn('server innerHTML: ', i);
        console.warn('client innerHTML: ', elm.innerHTML);
    }
  return false //HERE
}
 if(process.env.NODE_ENV ! = ='production' &&
      typeof console! = ='undefined' &&
      !hydrationBailed
  ) {
    hydrationBailed = true;
    console.warn('Parent: ', elm);
    console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children);
  }
  return false //HERE
}
Copy the code

This also allows the parameters of the activation function to be checked before the activation fails.

7) Last but not least, it is often possible, but sometimes more difficult, to make the activation error reappear.

8) You now see that one of our breakpoints has been triggered and the script has stopped executing

9) Now open the debugger console and write an element to retrieve the DOM element where activation failed. Using DOM elements, you will be able to trace activation errors back to one of your Vue components

10) Go to the next step

PS: This is a workflow adapted by user Budden73 to StackOverflow’s answer.

2. Make sure your HTML markup is reasonable

Now that you’ve found the code causing the problem, the first thing you need to do is make sure your markup (perhaps from an API) is valid. Code like this

Text

Note, however, that the tag does not allow images

Such a tag as a child element. These tags are the default tags for Vue transitions. You can change it by making it.

3. Resolve the inconsistency between the server and client

During the debugger, you can see the results from the server and redraw the client side. If there is a difference, you can take a look at how you get the data and what you render on the server or client side. A common problem is authentication of static web pages. Because HTML is generated stateless at build time and therefore does not know any authorization status, all authorization related parts of your application should be intended for client re-rendering. Otherwise, users with authorization status on the client side expect different HTML from the server side because of login. And then there’s only one option left…

4. Final avoidance measures:

The final option for resolving activation errors is to avoid component activation errors altogether. This is necessary for authentication-related components on statically generated pages, and sometimes for components that deliver content (for example, from third-party applications) that you cannot change but must embed.

As we learned at the beginning, activation only occurs when the component is rendered on both the server and client sides. To avoid activation failures, we use the tag to avoid re-rendering the server component. The only downside: This component is not included in the HTML returned by the server and does not help SEO.

Five, the summary

Let’s finish now that you know more:

What is activation and what does it do?

How did the activation fail and how do I detect the activation failure?

Common cause of activation failure

How to debug activation failures and resolve your application

I hope this article was informative and that you learned a thing or two. Have you encountered a cause of activation errors not described here, or have I missed a common cause? Feel free to send me a message on Twitter or via email. And as always – I’d be happy if you could spread the word and share your blog posts with your colleagues.

conclusion

Read this article to gain a lot, I hope you also ~~~