Hi,
I suggest that you use IAP function to erase/program on-chip flash, because the IAP function executes code in internal RAM and operate flash. as you know when you operate the flash, the flash can not be accessed/executed from.
If you write register to erase/program flash without using IAP function, So you have to disable all interrupt so that the flash is not accessed, furthermore, I suggest you copy the code to erase/program flash to internal SRAM and execute the code in SRAM to operate the flash.
Hope it can help you
BR
XiangJun Rong