3

I just added an "error boundary" to my React page with the "new" componentDidCatch feature in React 16.

However, when an error is thrown it shows:

Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development.

The React team recommends I change my webpack devtool from eval to cheap-module-source-map.

This does indeed work.

However, if you look at the performance chart, you'll see cheap-module-source-map is significantly slower than eval for rebuild time.

I can't afford to have webpack-dev-server run any slower. It already takes about 10 seconds to rebuild after a single character change to one of my JSX files. This isn't on a slow laptop either.

Is there anyway to display the error without changing my webpack devtool?

mpen
  • 272,448
  • 266
  • 850
  • 1,236

1 Answers1

2

There's been some discussion in facebook/react issue #10441.

It seems that the problem arises under some very specific conditions. I encounter this error too since installing load balancer and reverse proxy on my dev machine, and I haven't been able to solve this issue to my full satisfaction without enabling CORS. Here is what you may try:

  • try different Webpack devtools (from the table you've linked). For example, for my setup, cheap-eval-source-map works fine, but not cheap-module-eval-source-map.
  • set output.crossOriginLoading = 'anonymous' in Webpack development config to enable cross-origin loading of chunks
  • as a last resort, you may try to enable CORS server-side, globally or for specific routes, in development mode. Hypothetically, with CORS enabled you can use any devtool, alleviating performance problems, but...

    WARNING: enabling CORS this is a security hole and may be very dangerous, depending on what your security requirements are (see links below).

    Example of a simple Express middleware for enabling CORS on all routes:

    // Enable CORS in development
    if(config.IS_DEVELOPMENT) {
      app.use((req, res, next) => {
        res.header('Access-Control-Allow-Origin', '*')
        res.header('Access-Control-Allow-Headers',
          'Origin, X-Requested-With, Content-Type, Accept')
        next()
      })
    }
    

    You can make it smarter and only enable CORS selectively on bundle reloading routes. You may try the expressjs/cors package, which provides some more flexibility.

    Similarly, you can add CORS headers to webpack-dev-server devServer.headers

See also:

Ivan Aksamentov - Drop
  • 12,860
  • 3
  • 34
  • 61