wonday / react-native-pdf

A <Pdf /> component for react-native
MIT License
1.6k stars 555 forks source link

Warning: Can't call setState if Pdf was unmounted before source loaded #164

Closed scriptum closed 6 years ago

scriptum commented 6 years ago

While opening Pdf in modal dialog user can close pdf view before document was loaded. In this case PdfManager.loadFile promise tries to setState on unmounted component.

W/ReactNativeJS(31710): Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op,but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
W/ReactNativeJS(31710):     in Pdf (at DocumentPreviewScreen.js:123)

Version - "react-native-pdf": "^3.0.9"

This hot fix works for me (PdfView.js):

    componentDidMount() {

        PdfManager.loadFile(this.props.path, this.props.password)
            .then((pdfInfo) => {
                if(!this._unmount) // <-- little hack here
                this.setState({
                    pdfLoaded: true,
                    fileNo: pdfInfo[0],
                    numberOfPages: pdfInfo[1],
                    pageAspectRate: pdfInfo[3] === 0 ? 1 : pdfInfo[2] / pdfInfo[3]
                });
                if (this.props.onLoadComplete) this.props.onLoadComplete(pdfInfo[1], this.props.path);
            })
            .catch((error) => {
                this.props.onError(error);
            });

    }

...

    componentWillUnmount() {
        this._unmount = true; // <-- and here

        clearTimeout(this.scaleTimer);
        clearTimeout(this.scrollTimer);

    }
wonday commented 6 years ago

@scriptum thank you. release it at v3.0.11