You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[Due for payment 2026-11-19] [$175] [Sentry: APP-NAP] react-native-pdf throws "undefined is not a function" when a PDF download is canceled #106338
Sentry issue APP-NAP is an unhandled TypeError: undefined is not a function thrown inside react-native-pdf while a PDF download is canceled. It was found in the #quality-monitoring Sentry triage of Nov 6. No GitHub issue tracked it.
Evidence
First seen: Oct 21, 2026. Still active on Nov 9.
Impact: 649 events from 304 users in total. 411 events from 199 users in the last 7 days.
Mechanism:onunhandledrejection, so the error escapes as an unhandled promise rejection.
Stack (sample event, iOS HybridApp, release 9.5.26, view TransactionReceipt):node_modules/react-native-pdf/index.js:224 calls this.lastRNBFTask.cancel(...), reached from _downloadFile (line 179) and _prepareFile (line 161).
User-visible effect: not confirmed. The PDF may fail to render on the receipt screen.
What to check
Which platforms and releases are affected (split the Sentry issue by os.name and release).
Why lastRNBFTask.cancel is not a function at that point, and whether it happens when the user leaves the receipt before the download ends.
Whether the cancel can be guarded, or the rejection caught, in our PDF view wrapper.
Expected
Canceling a PDF download never throws, and the receipt screen shows the PDF or a clear error.
changed the title [-][Sentry: APP-NAP] react-native-pdf throws "undefined is not a function" when a PDF download is canceled[/-][+][$175] [Sentry: APP-NAP] react-native-pdf throws "undefined is not a function" when a PDF download is canceled[/+]on Nov 9, 2026
react-native-pdf loses the download task’s cancellation method, then calls it during a subsequent download. This explains both the TypeError and the unhandled rejection.
Confidence: medium overall. The defect is verified in the dependency versions pinned by the 9.5.26 release source; the precise trigger in the reported production events remains unconfirmed.
Blob-util attaches cancel() to its original download promise (fetch.js:337–348).
PDF stores the result of .fetch(...).progress(...).catch(...). That final .catch() returns a different promise without cancel() (index.js:264–284).
Another overlapping download calls lastRNBFTask.cancel() unconditionally (index.js:253–259).
_downloadFile is asynchronous, but _prepareFile does not await its result. Its synchronous try/catch therefore misses the rejection (index.js:192–248).
A changed source URI while the first download is pending is a supported route into this failure. Leaving the screen is not established as the trigger: unmount cancellation is commented out in this version (index.js:125–188). A network failure is not required.
What changes do you think we should make in order to solve the problem?
Add an App-owned dependency patch that:
Retains the original cancellable task separately from its promise handlers.
Safely coordinates cancellation and replacement loading.
Handles intentional cancellation without reporting a PDF-load failure.
Prevents stale callbacks from clearing or replacing the current download.
Observes asynchronous preparation failures and forwards genuine errors to onError.
A typeof cancel guard alone would suppress this exception without restoring cancellation. Wrapper-side error handling alone cannot catch the currently detached rejection.
Regression coverage and remaining verification
Test the actual dependency JavaScript with mocked downloads/filesystem:
Keep download A pending, then switch to uncached URI B.
Verify A is cancelled, B starts exactly once, and no unhandled rejection occurs.
Verify stale completions cannot overwrite B or clear its task.
Verify intentional cancellation does not display the error fallback.
Verify genuine failures reach onError; preserve cache-hit and unmount behavior.
Live Sentry data was unavailable. The OS/release breakdown, exact source-map correspondence, triggering sequence, and user-visible effect remain unverified; the issue’s event counts were not independently rechecked.
Next Steps for Contributor+ team: To accept:@MelvinBot implement [this](https://github.com/Expensify/App/issues/106338) to create a draft PR. To refine:@MelvinBot <your feedback> To reject: Explain why you are rejecting Melvin's proposal.
Please re-state the problem that we are trying to solve in this issue.
On native (iOS / Android, including TransactionReceipt), when a PDF receipt's source URI updates while an initial PDF download is still in flight, react-native-pdf throws an unhandled Promise rejection (TypeError: undefined is not a function at this.lastRNBFTask.cancel(...) in node_modules/react-native-pdf/index.js:224), recorded in Sentry as APP-NAP (onunhandledrejection).
What is the root cause of that problem?
There are two interacting root causes—one in our AttachmentModalBaseContent / AttachmentView state synchronization on TransactionReceipt that triggers back-to-back PDF loads with two different URIs, and one inside react-native-pdf's _downloadFile / _prepareFile implementation:
Why TransactionReceipt triggers two consecutive PDF loads (componentDidMount followed immediately by componentDidUpdate with a different uri):
When TransactionReceiptModalContent transitions from a loading/local state (isLocalFile: true -> isAuthTokenRequired: false when isFetchingWaypointsFromServer or a local draft resolves to a remote receipt URL) or when session.encryptedAuthToken hydrates/rotates in src/components/Attachments/AttachmentView/index.tsx:143,277:
PDFView first mounts <PDF source={{uri: sourceURL, cache: true, expiration: 864000}} /> with the initial URI (either without encryptedAuthToken while isAuthTokenRequiredState lags by one render, or with an empty ?encryptedAuthToken= before session.encryptedAuthToken is populated), and on the very next render updates source.uri to the authenticated URL while the first download is still in flight.
Why react-native-pdf throws an unhandled TypeError: undefined is not a function when source.uri updates mid-download:
In node_modules/react-native-pdf/index.js (_downloadFile, lines 264–284 of source / line 224 compiled):
ReactNativeBlobUtil.config(...).fetch(...).progress(...) returns a StatefulPromise that exposes .cancel(). However, chaining .catch(...) at the end returns a standard native Promise (where .cancel is undefined) and assigns that standard Promise to this.lastRNBFTask.
When source.uri changes on the next render, componentDidUpdate (line 132) checks if (this.lastRNBFTask && this.lastRNBFTask.cancel). Because this.lastRNBFTask.cancel is undefined, that condition evaluates to false, skipping cancellation and falling into the else branch (this._loadFromSource(this.props.source) -> _prepareFile -> _downloadFile) with this.lastRNBFTask still non-null.
At the start of _downloadFile (line 255), if (this.lastRNBFTask) calls this.lastRNBFTask.cancel(...) without checking .cancel, throwing TypeError: undefined is not a function.
Because _prepareFile (async (source) => { try { ... this._downloadFile(source, cacheFile); } catch (e) { ... } }, line 209) calls this._downloadFilewithout await, the rejected Promise from async _downloadFile bypasses _prepareFile's try / catch and escapes globally as onunhandledrejection.
What changes do you think we should make in order to solve the problem?
In AttachmentModalBaseContent/index.tsx, synchronize source and isAuthTokenRequiredState during render (or derive isAuthTokenRequiredForAttachmentView = source ? isAuthTokenRequiredState : isAuthTokenRequired) so sourceForAttachmentView and isAuthTokenRequired never lag by one render when sourceProp transitions from empty/local to remote.
In AttachmentView/index.tsx, if isAuthTokenRequired is true and !encryptedAuthToken, render the loading state (DefaultAttachmentView with shouldShowLoadingSpinnerIcon) rather than mounting <AttachmentViewPdf> with an unauthenticated URL that immediately changes on the next render.
Fix this.lastRNBFTask cancellation and promise handling in react-native-pdf via a new numbered patch patches/react-native-pdf/react-native-pdf+7.0.2+007+fix-cancel-download-task.patch (and update patches/react-native-pdf/details.md):
Store the ReactNativeBlobUtilStatefulPromise (from .fetch(...).progress(...)) on this.lastRNBFTaskbefore attaching .then(...) / .catch(...) so this.lastRNBFTask.cancel remains a valid function.
Guard typeof this.lastRNBFTask?.cancel === 'function' in componentDidUpdate, componentWillUnmount, and _downloadFile, and track a local const task = ... reference so stale completion callbacks from a canceled task do not clobber a newer this.lastRNBFTask or invoke _onError after intentional cancellation.
await this._downloadFile(source, cacheFile) inside _prepareFile so any unexpected error is caught by _prepareFile's try / catch and routed to this._onError(e) instead of escaping as an unhandled rejection.
What alternative solutions did you explore? (Optional)
Only patching react-native-pdf without fixing the two-render URI flip in AttachmentModalBaseContent / AttachmentView: Preventing the crash in react-native-pdf is necessary, but leaving the one-render isAuthTokenRequiredState lag in AttachmentModalBaseContent still causes TransactionReceipt to kick off and immediately abort an unauthenticated HTTP download on initial open. Fixing both eliminates the wasted network request and makes react-native-pdf cancellation safe under all URI updates.
— submitted with Antigravity on the contributor's behalf
The solution for this issue has been 🚀 deployed to production 🚀 in version 9.5.36-0 and is now subject to a 7-day regression period 📆. Here is the list of pull requests that resolve this issue:
If no regressions arise, payment will be issued on 2026-11-19. 🎊
The following checklist (instructions) will need to be completed before the issue can be closed. Please copy/paste the Contributor+ Checklist from here into a new comment on this GH and complete it. If you have the K2 extension, you can simply click: [this button]. If no checklist is needed for this issue, you can click: [no checklist button]
[Contributor] The offending PR and associated issue have been commented on, pointing out the bug it caused and why, so the author and reviewers can learn from the mistake.
[Contributor] If the regression was CRITICAL (e.g. interrupts a core flow) A discussion in #expensify-open-source has been started about whether any other steps should be taken (e.g. updating the PR review checklist) in order to catch this type of bug sooner.
N/A, not critical: an unhandled promise rejection, and in a rare race the previous receipt PDF was shown.
[Contributor] If it was decided to create a regression test for the bug, please propose the regression test steps using the template below to ensure the same bug will not reach production again.
I don't think a manual regression test is needed: it depends on the auth token changing while a PDF is still downloading, which QA can't time reliably. tests/unit/ReactNativePDFDownloadTest.tsx from Fix react-native-pdf throws undefined is not a function #106351 covers it.
PR 106351: by staszekscp (BEC and agency, no per-issue pay), merged 2026-11-10, production 2026-11-12, approved by mountiny. suneox posted the Reviewer Checklist.
Activity
melvin-bot commentedon Nov 9, 2026
Triggered auto assignment to Contributor-plus team member for initial proposal review - @suneox (
External)[-][Sentry: APP-NAP] react-native-pdf throws "undefined is not a function" when a PDF download is canceled[/-][+][$175] [Sentry: APP-NAP] react-native-pdf throws "undefined is not a function" when a PDF download is canceled[/+]melvin-bot commentedon Nov 9, 2026
Job added to Upwork: https://www.upwork.com/jobs/~022119659080543991764
MelvinBot commentedon Nov 9, 2026
Proposal
What is the root cause of that problem?
react-native-pdfloses the download task’s cancellation method, then calls it during a subsequent download. This explains both theTypeErrorand the unhandled rejection.Confidence: medium overall. The defect is verified in the dependency versions pinned by the 9.5.26 release source; the precise trigger in the reported production events remains unconfirmed.
Code evidence and failure sequence
react-native-pdf7.0.2 andreact-native-blob-util0.24.9.cancel()to its original download promise (fetch.js:337–348)..fetch(...).progress(...).catch(...). That final.catch()returns a different promise withoutcancel()(index.js:264–284).lastRNBFTask.cancel()unconditionally (index.js:253–259)._downloadFileis asynchronous, but_prepareFiledoes not await its result. Its synchronoustry/catchtherefore misses the rejection (index.js:192–248).A changed source URI while the first download is pending is a supported route into this failure. Leaving the screen is not established as the trigger: unmount cancellation is commented out in this version (
index.js:125–188). A network failure is not required.What changes do you think we should make in order to solve the problem?
Add an App-owned dependency patch that:
onError.A
typeof cancelguard alone would suppress this exception without restoring cancellation. Wrapper-side error handling alone cannot catch the currently detached rejection.Regression coverage and remaining verification
Test the actual dependency JavaScript with mocked downloads/filesystem:
onError; preserve cache-hit and unmount behavior.The existing native PDF tests mock out the dependency, so they cannot detect this defect.
No runtime reproduction was performed. Web testing cannot validate this path because web uses a different PDF renderer.
Live Sentry data was unavailable. The OS/release breakdown, exact source-map correspondence, triggering sequence, and user-visible effect remain unverified; the issue’s event counts were not independently rechecked.
Next Steps for Contributor+ team:
To accept:
@MelvinBot implement [this](https://github.com/Expensify/App/issues/106338)to create a draft PR.To refine:
@MelvinBot <your feedback>To reject: Explain why you are rejecting Melvin's proposal.
view run
HindsightWise commentedon Nov 9, 2026
Proposal
Please re-state the problem that we are trying to solve in this issue.
On native (
iOS/Android, includingTransactionReceipt), when a PDF receipt'ssourceURI updates while an initial PDF download is still in flight,react-native-pdfthrows an unhandled Promise rejection (TypeError: undefined is not a functionatthis.lastRNBFTask.cancel(...)innode_modules/react-native-pdf/index.js:224), recorded in Sentry asAPP-NAP(onunhandledrejection).What is the root cause of that problem?
There are two interacting root causes—one in our
AttachmentModalBaseContent/AttachmentViewstate synchronization onTransactionReceiptthat triggers back-to-back PDF loads with two different URIs, and one insidereact-native-pdf's_downloadFile/_prepareFileimplementation:Why
TransactionReceipttriggers two consecutive PDF loads (componentDidMountfollowed immediately bycomponentDidUpdatewith a differenturi):src/pages/media/AttachmentModalScreen/AttachmentModalBaseContent/index.tsx:93-103,sourceandisAuthTokenRequiredStateare mirrored into local state viauseEffect, butsourceForAttachmentView = source || sourcePropfalls back tosourcePropimmediately on the render wheresourcePropfirst becomes non-empty:TransactionReceiptModalContenttransitions from a loading/local state (isLocalFile: true->isAuthTokenRequired: falsewhenisFetchingWaypointsFromServeror a local draft resolves to a remote receipt URL) or whensession.encryptedAuthTokenhydrates/rotates insrc/components/Attachments/AttachmentView/index.tsx:143,277:PDFViewfirst mounts<PDF source={{uri: sourceURL, cache: true, expiration: 864000}} />with the initial URI (either withoutencryptedAuthTokenwhileisAuthTokenRequiredStatelags by one render, or with an empty?encryptedAuthToken=beforesession.encryptedAuthTokenis populated), and on the very next render updatessource.urito the authenticated URL while the first download is still in flight.Why
react-native-pdfthrows an unhandledTypeError: undefined is not a functionwhensource.uriupdates mid-download:node_modules/react-native-pdf/index.js(_downloadFile, lines 264–284 of source / line 224 compiled):ReactNativeBlobUtil.config(...).fetch(...).progress(...)returns aStatefulPromisethat exposes.cancel(). However, chaining.catch(...)at the end returns a standard nativePromise(where.cancelisundefined) and assigns that standardPromisetothis.lastRNBFTask.source.urichanges on the next render,componentDidUpdate(line 132) checksif (this.lastRNBFTask && this.lastRNBFTask.cancel). Becausethis.lastRNBFTask.cancelisundefined, that condition evaluates tofalse, skipping cancellation and falling into theelsebranch (this._loadFromSource(this.props.source)->_prepareFile->_downloadFile) withthis.lastRNBFTaskstill non-null._downloadFile(line 255),if (this.lastRNBFTask)callsthis.lastRNBFTask.cancel(...)without checking.cancel, throwingTypeError: undefined is not a function._prepareFile(async (source) => { try { ... this._downloadFile(source, cacheFile); } catch (e) { ... } }, line 209) callsthis._downloadFilewithoutawait, the rejected Promise fromasync _downloadFilebypasses_prepareFile'stry / catchand escapes globally asonunhandledrejection.What changes do you think we should make in order to solve the problem?
Prevent premature/split-render PDF downloads in
src/components/Attachments/AttachmentView/index.tsxandsrc/pages/media/AttachmentModalScreen/AttachmentModalBaseContent/index.tsx:AttachmentModalBaseContent/index.tsx, synchronizesourceandisAuthTokenRequiredStateduring render (or deriveisAuthTokenRequiredForAttachmentView = source ? isAuthTokenRequiredState : isAuthTokenRequired) sosourceForAttachmentViewandisAuthTokenRequirednever lag by one render whensourceProptransitions from empty/local to remote.AttachmentView/index.tsx, ifisAuthTokenRequiredistrueand!encryptedAuthToken, render the loading state (DefaultAttachmentViewwithshouldShowLoadingSpinnerIcon) rather than mounting<AttachmentViewPdf>with an unauthenticated URL that immediately changes on the next render.Fix
this.lastRNBFTaskcancellation and promise handling inreact-native-pdfvia a new numbered patchpatches/react-native-pdf/react-native-pdf+7.0.2+007+fix-cancel-download-task.patch(and updatepatches/react-native-pdf/details.md):ReactNativeBlobUtilStatefulPromise(from.fetch(...).progress(...)) onthis.lastRNBFTaskbefore attaching.then(...)/.catch(...)sothis.lastRNBFTask.cancelremains a valid function.typeof this.lastRNBFTask?.cancel === 'function'incomponentDidUpdate,componentWillUnmount, and_downloadFile, and track a localconst task = ...reference so stale completion callbacks from a canceled task do not clobber a newerthis.lastRNBFTaskor invoke_onErrorafter intentional cancellation.await this._downloadFile(source, cacheFile)inside_prepareFileso any unexpected error is caught by_prepareFile'stry / catchand routed tothis._onError(e)instead of escaping as an unhandled rejection.What alternative solutions did you explore? (Optional)
react-native-pdfwithout fixing the two-render URI flip inAttachmentModalBaseContent/AttachmentView: Preventing the crash inreact-native-pdfis necessary, but leaving the one-renderisAuthTokenRequiredStatelag inAttachmentModalBaseContentstill causesTransactionReceiptto kick off and immediately abort an unauthenticated HTTP download on initial open. Fixing both eliminates the wasted network request and makesreact-native-pdfcancellation safe under all URI updates.— submitted with Antigravity on the contributor's behalf
staszekscp commentedon Nov 9, 2026
Hey @mountiny ! I'm looking at the issue
11 remaining items
melvin-bot commentedon Nov 12, 2026
@suneox
The solution for this issue has been 🚀 deployed to production 🚀 in version 9.5.36-0 and is now subject to a 7-day regression period 📆. Here is the list of pull requests that resolve this issue:
undefined is not a function#106351If no regressions arise, payment will be issued on 2026-11-19. 🎊
The following checklist (instructions) will need to be completed before the issue can be closed. Please copy/paste the Contributor+ Checklist from here into a new comment on this GH and complete it. If you have the K2 extension, you can simply click: [this button]. If no checklist is needed for this issue, you can click: [no checklist button]
expensify-chore-bot commentedon Nov 17, 2026
@suneox Eep! 4 days overdue now. Issues have feelings too...
suneox commentedon Nov 18, 2026
Contributor+ Checklist:
[Contributor] The offending PR and associated issue have been commented on, pointing out the bug it caused and why, so the author and reviewers can learn from the mistake.
N/A. The bug is in
react-native-pdf: since 6.7.7,_downloadFilestores the promise returned by.catch()inlastRNBFTaskinstead of the download task, so it has nocancel(). It reached the App with the 6.7.3 → 7.0.1 bump in [Pre RN 0.81] Bumpreact-native-pdf#72204. It only shows when the PDF source changes while it's still downloading, so it couldn't reasonably be caught in that review, and the fix is going upstream in fix(download): don't report a canceled or replaced download through onError wonday/react-native-pdf#1057.[Contributor] If the regression was CRITICAL (e.g. interrupts a core flow) A discussion in #expensify-open-source has been started about whether any other steps should be taken (e.g. updating the PR review checklist) in order to catch this type of bug sooner.
N/A, not critical: an unhandled promise rejection, and in a rare race the previous receipt PDF was shown.
[Contributor] If it was decided to create a regression test for the bug, please propose the regression test steps using the template below to ensure the same bug will not reach production again.
I don't think a manual regression test is needed: it depends on the auth token changing while a PDF is still downloading, which QA can't time reliably.
tests/unit/ReactNativePDFDownloadTest.tsxfrom Fix react-native-pdf throwsundefined is not a function#106351 covers it.suneox commentedon Nov 18, 2026
APP-NAP is no longer happening after build
9.5.36-0, which includes #106351.expensify-chore-bot commentedon Nov 18, 2026
Triggered auto assignment to @mallenexpensify (
Awaiting Payment)expensify-chore-bot commentedon Nov 18, 2026
Payment Summary
Resolving PRs:
Fix react-native-pdf throws
undefined is not a function#106351Reviewer: @suneox owed $175 via NewDot
Contributor: @staszekscp does not require payment (Contractor)
BugZero Checklist (@mallenexpensify)
mallenexpensify commentedon Nov 20, 2026
Claude posting on behalf of Matt:
Ready. Job price: $175 (standard, no Help Wanted, assigned 2026-11-09).
suneox confirms the Sentry error stopped after 9.5.36-0. No deploy blockers.
Next: pay. No Caps+Y.
Evidence
PAYPREP v1