This happens because of a loose component holding the vibration motor. While tapping the phone does work, for me, it was only a temporary solution. The issue inevitably got more serious, and I’d end up beating the phone against my hand (not even tapping, at this point) every 1-2 minutes of using the phone. It was impossible to continue using the phone this way, so I took it to a third party service center (because authorized service centers in India suck and they refused to fix the issue) and had the issue fixed in 10 min and it cost me close to nothing. It’s an easy fix, all you need is to tighten the loose component/screw, so I suggest taking the phone in to a service center or repair shop to fix the issue for good.
Beating the phone against your hand is only a temporary fix. The issue is with a part that holds the Taptic Engine in place. When the part gets loose/dislocated, the rattling sound occurs. I think it’s best to just take it to an Apple Store and have them fix it. I took mine to a third party store (because I don’t have Apple stores in my country, and the authorized service centers don’t fix these issues), but my phone’s fine now. It was a really simple fix.
I had this issue a couple months back and had decided to follow this thread. I got my phone fixed a few days after I noticed the issue. The issue was that a small component holding the Taptic Engine in place was loose and out of place. It was a simple fix, but compromised the phone’s water resistance. This is because Apple service centers in my country don’t fix these issues, so I had to go to a third party repair store (where obviously, replacing water resistance seals isn’t available). If you live in a country where official Apple stores exist, you should get your phone fixed there. Either way, it was a simple and rather inexpensive fix.