Viktor Kireev
Viktor Kireev

Reputation: 1250

Error in react event handler is fired multiple times

If error happens in react event handler (onChange in this case) it is displayed two times in console. Is it correct? Maybe I am doing something wrong?

onChange handler is called once.

I am going to setup monitoring on my page and do not want to have duplicated error.

Tested in react v16.

https://codesandbox.io/s/480y71xo00

import React from 'react';
import { render } from 'react-dom';
import Hello from './Hello';

class App extends React.Component {
  constructor(props){
    super(props);
    this.state = { text: '' };
  }

  onChange(event){
    console.log('Call unknown function once');
    //!!!
    what();

    this.setState({
      text: event.target.value
    });
  }

  render(){
    const {text} = this.state;

    return (
      <div>
        <Hello name="CodeSandbox" />
        <h2>Start editing to see some magic happen {'\u2728'}</h2>
        <input type="text" value={text} onChange={this.onChange.bind(this)}/>
      </div>
    );
  }
}

render(<App />, document.getElementById('root')); 

If you type something in input:

In Chrome enter image description here

But in Safari errors look like this: enter image description here

Upvotes: 0

Views: 165

Answers (1)

Dyo
Dyo

Reputation: 4464

This behavior is intended, this is explained in https://github.com/facebook/react/issues/10384 and discussed here : https://github.com/facebook/react/issues/10474

Here's the explanation from Dan Abramov :

For context, the reason it happens is because we intentionally let the browser interpret an error as uncaught before we rethrow. The justification is discussed in #10474.

If you follow the advice in the error and add an error boundary (which you should!), you will only see the error once. So that's not a huge problem in day-to-day workflow. In fact it nudges people to add error boundaries which is nice.

Another justification for this is that if you accidentally swallow an error we still print it once. That alone makes this worth it IMO. We’ve had hundreds of comments and dozens of issues caused by people swallowing their own errors, and the fact that we will print them at least once now seems like enough benefit to compensate for printing them twice when they’re uncaught, un-swallowed, and don’t have a boundary.

Upvotes: 2

Related Questions